Creating a reusable button component in React
Learn how to create a reusable button component in React without having business logic.
Reusable components are the React components that can be used multiple times across application code. To make it reusable it should be devoid of business logic.
Let’s create a Button component in React that returns a button.
function Button(props) { return ( <button className="button" onClick={props.handleClick}> Submit </button> ); }
We can pass any function to the Button component through the handleClick prop and this make this component reusable.
function handleClick(event) { getData(event.target.value); } function App() { return ( <div className="app"> <Button handleClick={handleClick} /> </div> ); }
The above is an example for a single function call. We can use multiple button components inside App component
function getData(event) { get((event.target.value)); } function save(event) { saveData(event.target.value)); } function App() { return ( <div className="app"> <Button handleClick={getData} /> <Button handleClick={save} /> </div> ); }