How to Create a Reusable Button Component in React

The article delves into the world of reusable code. We learn how to create a reusable button component in React making the writing of code more efficient and maintainable.

Create a Reusable Button Component in React
Create a Reusable Button Component in React

How to Create a Reusable Button Component in React

React makes it so easy to build efficient and maintainable code. With React, you can write reusable code to ensure you are not writing duplicate code which is very inefficient.

In this article, I will show you how to create a Button Component that can be reused all over your code. A Button makes a good candidate for this because it is almost impossible to lack a button in any app. It is also used in more than one place within your app.

let's see how to make the Button Component

Prerequisites

Before you get started:

  • Ensure you have Node.js and npm installed on your machine.
  • A basic understanding of React

Create a React Project

You can create a basic React app using the command below.

npx create-react-app button-component

Call your app anything you wish. I call mine button-component because that is what we are doing in this demo.

Alternatively, you can use Vite to create a React Project

Once done, cd into the project folder and open it using your favorite editor. I am using Visual Studio Code

cd button-component

Project Structure

Delete everything in the /src folder then Create an "index.js" file and an "App.js" file in the /src folder.

Also, create a components folder in the /src folder. Insider the components folder, create a Button.js file

Here is what your folder structure should look like.

node_modules
public
src
  Component
  --Button.js
--App.js
--index.js
.gitignore
package-lock.json
package.json
README.md

  • Inside the index.js file, add the code below.

    // index.js
    
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    
    
  • Inside the App.js file create a react fragment and import the Button Component as shown below. The app should return the Button component as JSX.

    // App.js
    
    import Button from "./components/Button"
    function App() {
      return (
        <>
        	<Button />
        </>
      );
    }
    
    export default App;
    
  • Inside the Button component, add the code below. For testing purposes, the button returns a paragraph with the text "Hello World". We'll fix that in a few.

    // Button.js
    
    import React from 'react'
    
    const Button = () => {
      return (
        <p>Hello World!</p>
      )
    }
    
    export default Button
    

Run the app in your terminal to make sure that everything is working using the command below.

npm start

If everything went correctly, your app should open up in the localhost:3000 with the text "Hello World".

Img 1.png

Writing the Button Component

Now that we know everything is working, Let's work on the Button Component.

Open Button.js and return a button instead of a paragraph as shown below

// Button.js

import React from 'react';

const Button = ({ onClick, label, type }) => {
  return (
    <button type={type} onClick={onClick}>
      {label}
    </button>
  );
};

export default Button;

Notice we have 3 props being passed into the function.

  • onClick: This is a function that should be called when the button is clicked.
  • label: This is the text content of the button.
  • type: This represents the type of button eg. button, submit, reset, etc.

These three props are what make the button reusable.

Styling the Button

Style your button as you please. Here is some basic styling for my button.

Create a new file named Button.css in the same components folder then add the css inside.

/* Button.css */

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  margin: 4px;
}

button:hover {
  background-color: #45a049;
}

Import the button styles inside the button component as shown below.

// Button.js

import React from 'react';
import './Button.css';

// ... rest of the code

That is our button fully done.

Img 2.png

Using the Reusable Button Component

With the Button done, we can import it into any other React component that needs the button. In this case, we use App.js to demonstrate.

Currently, this is how our App.js file looks like

// App.js

import Button from "./components/Button";

function App() {
  return (
    <>
      <Button />
    </>
  );
}

export default App;

Our App.js file returns the Button Component in the JSX. Let's pass down the props to see the reusability in action.

We need the onClick, type, and label props passed down to the button.

The type of our Button is "button" and the label is going to be "Click me"

The onClick prop is a function that has to be defined inside the App function as shown below.

// App.js

import React from 'react';
import Button from './components/Button';

const App = () => {
    
  //The onClick handle function   
  const handleClick = () => {
    alert('Button Clicked!');
  };

  return (
    <div>
      <h1>Reusable Button Component Demo</h1>
      <Button onClick={handleClick} label="Click me" type="button" />
    </div>
  );
};

export default App;

Notice our JSX Button now has the props defined. We can add another button below this one with the following props. onClick= {handleClickTwo} label={Click me Two} and type={button}. The onClick handler will look like this

const handleClickTwo = () => {
    alert('Button Two Clicked!');
  };

Here is what the code will look like.

// App.js

import React from 'react';
import Button from './components/Button';

const App = () => {
    
  //The onClick handle function   
  const handleClick = () => {
    alert('Button Clicked!');
  };
    
  const handleClickTwo = () => {
    alert('Button Two Clicked!');
  };

  return (
    <div>
      <h1>Reusable Button Component Demo</h1>
      <Button onClick={handleClick} label="Click me" type="button" />
      <Button onClick={handleClickTwo} label="Click me Two" type="button" />
    </div>
  );
};

export default App;

Run your Application

Save your changes and run your React application:

npm start

You should see the following on your browser.

Img 3.png

We created one button and reused it to have two buttons. We can add as many buttons as we want. That is the power of reusability in React.

If you click the first button, you should see an alert on your browser saying "Button Clicked".

Img 4.png

If you click the second button, you should see an alert saying "Button Two Clicked"

Img 5.png

This shows that the same button has different functionalities. This is awesome. It makes writing code so easy.

If you got to here, congratulations, you have set up a reusable button component and have understood the power of reusability.

Wrapping up

In this article, we have seen how to create a reusable button component in React. You can use the power of reusability to make anything thing that repeats in your code once and reuse it as many times as you wish. In this case, we reused a button and you can see how easy it was and efficient.

If you enjoyed reading, make sure to subscribe and share the article with interested parties.

Thanks for reading : )

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.