I’m new to React, I’m working on the Github Asabeneh Yetayeh 30 Days Of React repo. The repo says make a reusable component. What does reusable component mean? Does it mean a button with UseState or onClick? Is there any simple example, or document, video about it?
React reusable component construction
>Solution :
A reusable component in React is a piece of code that can be used multiple times in different parts of your application. It encapsulates a specific functionality or UI, making it easy to maintain and reuse.
For example, a reusable button component might have its own styling, state, and onClick logic. Here’s a simple example:
import React, { useState } from 'react';
const ReusableButton = ({ onClick, label }) => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
onClick && onClick();
};
return (
<button onClick={handleClick}>
{label} - Clicked: {count} times
</button>
);
};
export default ReusableButton;
You can use this component in different parts of your app like this:
import React from 'react';
import ReusableButton from './ReusableButton';
const App = () => {
const handleButtonClick = () => {
console.log('Button clicked!');
};
return (
<div>
<ReusableButton onClick={handleButtonClick} label="Click me" />
<ReusableButton onClick={handleButtonClick} label="Another button" />
</div>
);
};
export default App;
This way, you can easily reuse the button logic and appearance without duplicating code. You can find more information in the React documentation on components and props. Additionally, online tutorials and videos on React component reusability can provide further guidance.