React

Reusable Component In React

Hello Fellow Developers, Welcome Back to another Blog. In this Blog we are gonna talk about how to make a react component reusable.

React is basically a application which contains a bunch of components in a component tree. We can make a component more reusable by turning it from specific to more generic. We can achieve it by offering an API for the component. Component’s API in react  is its Props.

import React from 'react';

const App = () => {
  const click= () => console.log('Clicked!');

  return (
    <div>
      <button type="button" onClick={click}>
        Click me!
      </button>
    </div>
  );
};

export default App;

In order to make this HTML button reusable in React, we have to extract it to its own component. Let’s define a Button component for it.

import React from 'react';

const App = () => {
  return (
    <div>
      <Button />
    </div>
  );
};

const Button = () => {
  const click= () => console.log('Clicked!');

  return (
    <button type="button" onClick={click}>
      Click me!
    </button>
  );
};

export default App;

Button component as element in React’s JSX creates every time a new instance of this Button component. Even though the component is reusable in React’s perspective, it isn’t really reusable yet, because every Button component implements the same behavior.

import React from 'react';

const App = () => {
  return (
    <div>
      <Button />
      <Button />
    </div>
  );
};

Let’s change by giving the Button component of an API which is our interface to command our Button component from the outside.

const Button = ({ click}) => {
  return (
    <button type="button" onClick={click}>
      Click me!
    </button>
  );
};

Now, in your main or app component using the Button component, you can pass the your click handler function as props to the component, but specify it for each Button component individually:

const App = () => {
  return (
    <div>
      <Button
        click={() => console.log('Clicked One!')}
      />
      <Button
        click={() => console.log('Clicked Two!')}
      />
    </div>
  );
};

That’s it you have achieved how to change your components into reusable components. That’s it for this blog.

Krutvik Devmurari

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago