How to create button component in react js?

Hi Friends 👋,

Welcome To aGuideHub!

To create button component in React js, you have to use the button component. It will create button component in react js.

Today, I am going to show you, how to create button component in react js.

Table of contents

  • Set up the React project.
  • Import necessary components.
  • Create the button component.

Let’s start with the first step.

Step 1: Set up the React project.

First you have to install the React project. You should use create-react-app command to create a new React project.

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

Step 2: Import necessary components.

You have to import the react component, which you can use in your React component.

import * as React from 'react';

Step 3: Create the button component.

To create a button component. You have to use the button component and set the type of button.

    <button type="button" onClick={onClick}>
      {children}
    </button>

ReactJS create button component example.

The below code is an example of, This Button component takes two props: onclick and children. This looks like an HTML button element with the onclick prop set to the onclick prop passed down from the parent component, and the button’s text content set to the children prop passed in from the parent component.

App.js

import * as React from 'react';

const App = () => {
  const [isOpen, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(!isOpen);
  };

  return (
    <div>
      <Button onClick={handleClick}>Toggle</Button>

      {isOpen && <div>Content</div>}
    </div>
  );
};

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

export default App;

Check the output of the above code example.

React, button-component

Here, we are provided code sandbox links for the above program create button component in React js. Then you can use whenever you went and do the changes as per your requirements.

Try it Yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts