Creating a React Accordion — The easy way !!

Prem Das
3 min readFeb 19, 2020

Accordions are useful when you want to toggle between hiding and showing large amount of content. An accordion menu is a vertically stacked list of headers that can be clicked to reveal or hide content associated with them.

Creating accordions can sometimes be a hideous task. But, I am here to guide you through. I have created a demo app for this and in this implementation, one panel of the accordion is always expanded, and only one panel may be expanded at a time. Apart from this, we can toggle any panel.

At the end of this article you can achieve the below thing :-

So, brace up yourself and let’s start.

My folder structure is as shown below :-

First of all, lets prepare up the skeleton of the app. My DOM is as follows :-

After getting the DOM and CSS ready, my app will look somewhat like this :-

You can refer to my css in my github profile :-

https://github.com/premdas92/React-Accordion

Now, our job is to hide the panel body and make it visible only when its respective heading i.e, Item 1, Item 2 etc., is clicked.

There are two things that we need to take care of :-

  1. Only the panel which is clicked should open and close. It should not affect the other panels.
  2. If a panel is left open and we click on some other panel then the current panel should open up and the latter should close.

Lets close our eyes now and thank the genius creator of React for he has provided us with “states” — a very beautiful React concept.

We are going to handle the functioning of the accordion using the states.

Now let us declare the states and the onClick function.

I have used a function called toggleAccordian to handle the accordion. In this function I am checking if the index (sent as parameter) is equal to the selectedIndex(state, which has been set to -1 by default).

If the selectedIndex is equal to the index, then this is the panel that has to open.

So, this.state.selectedIndex === index is our weapon (I will call it Thor’s Mjölnir)

Wrap the “body” class with this condition. Add this condition in “symbol” class also to change the + (plus) to — (minus) on click.

Your accordion is ready to rock and roll now.

You can find my full source code on the below github link :-

https://github.com/premdas92/React-Accordion

Thanks for reading this article. Stay in touch !!

--

--