DEV Community

Cover image for How to Make Accordion in React
ReactJS Guru
ReactJS Guru

Posted on • Originally published at reactjsguru.com

How to Make Accordion in React

In this article, we will make a simple accordion in react. Accordion is useful when we need to create some application user interactive. Basically, we will create a bunch of questions and if we click on the question, then the div will expand and show us the answer.

So this is going to be a very fun project to do and as a beginner it will teach us more because we will use some additional package like styled component. Also, we will make this accordion very dynamic like we can add question and answer in certain component and all effects will be reflected over the application. So let’s make it step-by-step.

Pre-requisite to Make Accordion in React

  • Basic knowledge of ReactJS.
  • Basic knowledge of React hooks.
  • Basic knowledge of React props.
  • Good knowledge of React Components.

Setting Up Project

Now firstly, we need to add two packages: (1) styled-components (2) react-icons.

Then we need some basic components like Accordion.js, where we will add main logic of the application. And Data.js component, where we will add questions and answer. We have to modify App component, here we imported Accordion, and we just called Accordion in return statement.

`import './App.css';
import Accordion from './Components/Accordion';

function App() {
return ;
}

export default App;
`

Adding Data in Component

Now, before adding main logic, we will add our data like question and answer in Data component. We have added only three data and more data can be added which will reflect over the application.

export const Data = [
{
question: 'What do you call a dog magician?',
answer: 'A labracadabrador.'
},
{
question: 'What do you call a funny mountain?',
answer: 'Hill-arious.'
},
{
question: 'What did the astronaut say when he crashed into the moon?',
answer: 'I Apollo-gize.'
}
];

Read More

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

HTML has this functionality built-in (use the summary and details elements) - example here. No JS required

Collapse
 
reactjsguru profile image
ReactJS Guru

yes it is possible