Accordion in React
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.
Project Setup
Create a new project using create-react-app
Now Let’s create a new component for questions and import it in App.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
React Icons
Let’s install React Icons for Accordion menu and import few icons into our new component.
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.
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.
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
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.
If the condition is true, exp1 is executed
If the condition is false, exp2 is executed
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.