Buttons are undeniably important UI Components of any react application, buttons might be used in scenarios such as submitting a form or opening a new page. You may build reusable button components in React.js that you can utilize throughout different sections of your application. As a result, maintaining your application will be simpler and your code will be kept DRY (Don't Repeat Yourself).
You must first create a new file in your components folder named Button.jsx in order to construct a reusable button component. The next step is to define the function "Button," which accepts the parameters text and onClick.
The text that will be displayed on the button is contained in the text prop. When the button is clicked, a function specified by the onClick prop will be called.
Finally, you must return a "button" element that has the text prop set to the text to be displayed on the button and the onClick prop set to the handler for the button's onclick event.
Here is an example of a reusable button component in React.js:
const Button = ({ text, onClick }) => { return ( <button type="button" style={{ margin: 10px, }} onClick={onClick} > {text} </button> ); }; export default Button;
Once you have created your reusable button component, you can import it into any other component that you want to use it in. For example, you could create a component called MyComponent that uses the Button component to render a button with the text "Click me!".
Here is an example of how to use the Button component in another component:
import Button from "../components/Button"; const MyComponent = () => { return ( <div> <Button text="Click me!" onClick={() => console.log("Button clicked!")} /> </div> ); }; export default MyComponent;
This will render a button with the text "Click me!". When the button is clicked, the console.log function will be called and the message "Button clicked!" will be logged to the console.
You can also use the Button component to create buttons with different styles. For example, you can add a class to the button element to apply a custom style. For example:
import Button from "../components/Button"; const MyComponent = () => { return ( <div> <Button text="Click me!" onClick={() => console.log("Button clicked!")} className="my-custom-class" /> </div> ); }; export default MyComponent;
This will render a button with the text "Click me!". The button will also have the class my-custom-class applied to it. You can use this class to style the button in your CSS file.
The above is the detailed content of How to create a reusable Button component in ReactJS. For more information, please follow other related articles on the PHP Chinese website!