@rollin
To create a reusable React.js component, you can follow these steps:
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.