How to create a reusable React.js component?

Member

by rollin , in category: Javascript , 6 months ago

How to create a reusable React.js component?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 6 months ago

@rollin 

To create a reusable React.js component, you can follow these steps:

  1. Identify the common functionality or UI elements that you want to reuse in multiple places.
  2. Create a new file for your component and give it a meaningful name. For example, if you are creating a button component, you could name it "Button.js".
  3. In your component file, import the necessary dependencies. Typically, you will need to import the React library and any other external libraries or components you plan to use.
  4. Define your component as a JavaScript function or class that extends the React.Component class. For a functional component, use the function declaration syntax. For a class-based component, create a class that extends React.Component.
  5. Write the JSX code that represents the component's UI. This is where you define the structure and appearance of the component. You can use props to pass data or behavior into the component.
  6. Export your component as a default export at the end of the file. This allows you to import and use the component in other parts of your application.


Example of creating a reusable button component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Button.js

import React from 'react';
import PropTypes from 'prop-types';

function Button({ onClick, label }) {
  return (
    <button onClick={onClick}>
      {label}
    </button>
  );
}

Button.propTypes = {
  onClick: PropTypes.func,
  label: PropTypes.string.isRequired,
};

export default Button;


You can then use the Button component in other parts of your application by importing it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// App.js

import React from 'react';
import Button from './Button';

function App() {
  const handleClick = () => {
    console.log('Button clicked');
  };

  return (
    <div>
      <Button onClick={handleClick} label="Click me" />
    </div>
  );
}

export default App;


By creating reusable components, you can easily share and reuse code, improve maintainability, and promote consistency in your React.js application.