askvity

How Do I Create a Custom Button Component in React?

Published in React Component Development 5 mins read

Creating a custom button component in React involves a few key steps: setting up your project, creating the component file, styling it, and then using it within your application.

This approach enhances reusability, maintainability, and readability in your React projects.

Steps to Create a Custom Button Component

Based on the provided steps, here's how you can build your own reusable button:

1. Step 1: Set Up Your Project

First, you need a React project environment. A common way to start is by using Create React App. If you don't have a project set up yet, you can create one using your terminal:

npx create-react-app my-custom-button-app
cd my-custom-button-app
npm start

This command sequence creates a new directory my-custom-button-app, sets up a basic React project inside it, navigates into the directory, and then starts the development server.

2. Step 2: Create the Button Component

Inside the src folder of your React project, create a new file specifically for your button component. A descriptive name is helpful, such as CustomButton.js or CustomButton.jsx.

This file will contain the code for your reusable button component.

// src/CustomButton.js

import React from 'react';

function CustomButton(props) {
  // The component receives props, like text content (children) and click handlers
  return (
    <button
      onClick={props.onClick} // Attach click handler passed via props
      className={props.className} // Allow passing CSS classes for styling
      style={props.style} // Allow passing inline styles
    >
      {props.children} {/* Display the text content passed as children */}
    </button>
  );
}

export default CustomButton;

In this basic structure:

  • It's a functional component named CustomButton.
  • It accepts props. Common props for a button include onClick (a function to run when clicked) and children (the text or elements inside the button).
  • It renders a standard HTML <button> element.
  • props.onClick, props.className, and props.style are passed down to the native button, making the custom component flexible.
  • props.children is rendered inside the <button>, allowing you to easily set the button's label.

3. Step 3: Style the Button

Styling is crucial for making your custom button look good and fit your application's design. You can style your component using various methods:

  • CSS Files: Create a CSS file (e.g., CustomButton.css) and import it into your component file.
  • CSS Modules: A popular method (CustomButton.module.css) to scope styles to avoid conflicts.
  • Styled Components: A library for writing CSS directly in your JavaScript.
  • Inline Styles: Passing style objects directly via the style prop (less common for complex styles).

Let's use a simple CSS file example:

src/CustomButton.css

/* src/CustomButton.css */

.custom-button {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.custom-button:hover {
  background-color: #0056b3;
}

src/CustomButton.js (updated to import CSS)

import React from 'react';
import './CustomButton.css'; // Import the CSS file

function CustomButton(props) {
  return (
    <button
      onClick={props.onClick}
      className={`custom-button ${props.className || ''}`} // Apply the base class and any passed class
      style={props.style}
    >
      {props.children}
    </button>
  );
}

export default CustomButton;

By adding className="custom-button", the styles defined in CustomButton.css are applied to the button element. The expression `custom-button ${props.className || ''}` allows consumers of the component to also pass their own CSS classes via the className prop, which will be appended to the base class.

4. Step 4: Use the Custom Button in Your App

Now that you've created and styled your CustomButton component, you can use it anywhere in your application by importing it.

src/App.js

// src/App.js

import React from 'react';
import CustomButton from './CustomButton'; // Import the custom button
import './App.css'; // Or your main app styles

function App() {
  const handleButtonClick = () => {
    alert('Button clicked!');
  };

  return (
    <div className="App">
      <h1>My App</h1>
      {/* Using the CustomButton */}
      <CustomButton onClick={handleButtonClick}>
        Click Me
      </CustomButton>

      {/* Using the CustomButton with different text */}
      <CustomButton onClick={() => console.log('Second button clicked')}>
        Learn More
      </CustomButton>

      {/* Using the CustomButton with a custom class (if styled) */}
      {/* Assuming you have a .secondary-button style in CustomButton.css or App.css */}
      {/* <CustomButton className="secondary-button">
        Secondary Action
      </CustomButton> */}
    </div>
  );
}

export default App;

In App.js:

  • We import the CustomButton component.
  • We define a function handleButtonClick that will be executed when the first button is clicked.
  • We render <CustomButton> components, passing the desired text as children and the onClick function as a prop.

Enhancing Your Custom Button

To make your custom button even more robust, consider adding:

  • Prop Validation: Use prop-types to define the expected types of props (onClick should be a function, children can be node, etc.).
  • Loading State: Add a loading prop that changes the button's appearance and disables clicks.
  • Disabled State: Add a disabled prop that passes the disabled attribute to the native button.
  • Size/Variant Props: Props like size ("small", "medium", "large") or variant ("primary", "secondary", "outline") to easily apply different style variations.

Summary Table of Basic Button Props

Prop Name Type Description Example Usage
children ReactNode (text/JSX) The content displayed inside the button. <CustomButton>Submit</CustomButton>
onClick function Function to call when the button is clicked. <CustomButton onClick={myFunc}>
className string Additional CSS class names to apply. <CustomButton className="btn-lg">
style object (CSSProperties) Inline styles to apply. <CustomButton style={{ color: 'red' }}>

By following these steps and incorporating additional features, you can create versatile and reusable custom button components tailored to your application's needs.

Related Articles