Create an Accordion Component in React

Today we’ll show you how to create an accordion component in React JS. In other words, we can say how to create a collapsible component in ReactJS with expand and collapse options.

In this article, we will create a reusable component where we can manage the single accordion/collapsible box based on the given props.

Steps to implement an accordion component

  1. Create react application
  2. Import font-awesome library
  3. Design the accordion/collapsible panel
  4. Import panel in the main component
  5. Output

1. Create react application

Let’s create a react application using create-react-app. If you don’t know how to do it then refer to this link.

We have used the following command to create a react app.

2. Import font-awesome library

To display expand and collapse icons, we will use the font awesome library. If you want to use the pure css or image icon then you can ignore this step.

Add the below stylesheet in the head part of the public/index.html file.

3. Design the accordion/collapsible panel

In the next step, we will create a reusable accordion component with expand and collapse icons.

Check out the following code to create an accordion component.

In the above code, we will receive the several attributes via props such as title, isExpand and children. We used the default parameter as isExpand = false to manage the default behaviour of the panel.

To manage the expand and collapse features, we used the state variable and here we used the react hooks to manage the state using the useState method.

Use the following CSS to design the panel.

index.css

4. Import panel in the main component

Now we will use the accordion panel in the main component same as the others.

You can see we have set the isExpand={true} for the second accordion so at the initial time it will be expanded.

5. Output

Finally, let’s combine all codes together and see how it looks.

App.js

Run the project and check the output in the browser.

Output - Create an Accordion Component in React - Clue Mediator
Output – Create an Accordion Component in React – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *