Create custom button in react js | HSPDev



To create a custom button in a React.js application, you can define a React component for the button and style it using CSS. Here's a step-by-step guide to creating a custom button component


To create a custom button in a React.js application, you can define a React component for the button and style it using CSS. Here's a step-by-step guide to creating a custom button component:

  1. Create a new React component for the custom button. You can do this by creating a new JavaScript file (e.g., CustomBtn.js) and defining your component there.
jsx
// CustomBtn.js import React from 'react'; const CustomBtn = ({ text, onClick }) => { return ( <button className="custom-button" onClick={onClick}> {text} </button> ); }; export default CustomBtn;

In this example, we've created a functional component called CustomBtn. It takes two props: text (the button label) and onClick (the click event handler).

  1. Style your custom button using CSS. You can create a separate CSS file (e.g., CustomBtn.css) and define your button styles there.
css
/* CustomBtn.css */ .custom-button { background-color: #007bff; /* Set your desired background color */ color: #fff; /* Set your desired text color */ padding: 10px 20px; /* Adjust padding as needed */ border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } .custom-button:hover { background-color: #0056b3; /* Change the color on hover if desired */ }
  1. Import and use your custom button component in your application. You can import the CustomBtn component and render it within your main application file (e.g., App.js).
jsx
// App.js import React from 'react'; import CustomBtn from './CustomBtn'; // Import your custom button component import './App.css'; // Import your application's CSS function App() { const handleClick = () => { alert('Button clicked!'); }; return ( <div className="App"> <h1>Custom Button Example</h1> <CustomBtn text="Click here" onClick={handleClick} /> </div> ); } export default App;
  1. Make sure to include your custom button's CSS file in your application's entry point (e.g., index.js) or import it where needed.
jsx
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // Import global styles import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); reportWebVitals();
  1. Finally, you can start your React application to see your custom button in action:
sql
npm start

Your custom button should now be displayed in your React application with the specified styles and functionality. You can further customize the button's appearance and behavior by modifying the CSS and props passed to the CustomBtn component.