Accordion in React

Muktha Sai Ajay
4 min readJun 1, 2022

--

Building Accordion from scratch

Accordion menus can be used to display FAQs, allows users to toggle between hiding and displaying content in a webpage. In this blog we will cover how to develop an accordion menu in React from scratch.

Photo by Arnold Francisca on Unsplash

Project Setup

Create a new project using create-react-app

Creating React App

Now Let’s create a new component for questions and import it in App.js

Question.js

Now we need data to display content in accordion, we will create a new file for data and add some dummy data inside it and import the file in App.js

data.js

React Icons

Let’s install React Icons for Accordion menu and import few icons into our new component.

Installing React Icons
importing icons in Question.js

Now, we will map the data and pass data as props from App component into Question component. As we have five questions, we will get five questions in the display.

App.js
Output

We will accept the data into Question component and lets display the data. You can find style sheet in the code link mentioned at last.

Question.js
Output

Create a useState hook of boolean type that will conditionally render the information based on boolean value. If the state value is true, it will display additional information of the question, if it’s false, it will hide the information. We need to use AND logic (&&) to implement this functionality

Question.js

How to Open and Close the Accordion Menu

We will attach an on-Click event that will toggle the showDetails state and will display accordingly. In addition to that, to change the icons dynamically based on the condition we will use Ternary operator. It evaluates the condition and executes the block of code based on the condition.

Ternary operator syntax

If the condition is true, exp1 is executed

If the condition is false, exp2 is executed

Added Ternary Operator
Final Output
Final Output

You can find the link for the code below

Thank you for reading my article. I will be happy to hear your opinions. Follow me on Medium to get updated on my latest articles. You can also connect with me on Linkedin and Twitter. Check out my blogs on Machine Learning, React and Deep Learning.

--

--