How to create Accordion in ReactJS?


A UI element called an accordion enables user to expand and compress content portions. A great method to add interactivity to your online application and make it simpler for visitors to explore and find the information they need is to create an accordion in ReactJS.

This article will walk you through the steps required to create an accordion in ReactJS and provide sample code to get you started.

Step 1: Setting up the React Project

To get started, you must have a React project set up. The create-react-app command can create a new project if you don't currently have one.

npx create-react-app my-app
cd my-app
npm start

This creates a new project in the directory "my-app" and launches a development server so you can preview your changes online.

Step 2: Creating the Accordion Component

After setting up a fundamental React project, we can develop a new component for our accordion. In the project's src directory,create a new file called Accordion.js

Accordion.js

import React, { useState } from 'react';
function Accordion({ items }) {
   const [activeIndex, setActiveIndex] = useState(-1);
   const handleClick = (index) => {
      setActiveIndex(index === activeIndex ? -1 : index);
   };
   return (
      <div>
         {items.map((item, index) => (
            <div key={item.title}>
               <button onClick={() =>handleClick(index)}>{item.title}</button>
               {index === activeIndex && <p>{item.content}</p>}
            </div>
         ))}
      </div>
   );
}
export default Accordion;

We are importing React and the useState hook from the react package into this code.

The useState hook allows us to add state to our component, in this case, the activeIndex. When the button is clicked, we use the setActiveIndex function to change the state and rerender the component with the new activeIndex. We set the initial state to -1.

Additionally, we render the accordion items by iterating through the items parameter using the map method.

Step 3: Adding the Accordion to the App

We need to incorporate the accordion component into our app now that we have it. The Accordion component will be imported into the App.js file and added to the JSX in order to accomplish this.

App.js

import React from 'react';
import Accordion from './Accordion';
const items = [
   {
      title: "Section 1",
      content: "This is the content of section 1"
   },
   {
      title: "Section 2",
      content: "This is the content of section 2"
   },
   {
      title: "Section 3",
      content: "This is the content of section 3"
   }
]
function App() {
   return (
      <div>
         <Accordion items={items} />
      </div>
   );
}
export default App;

Step 4: Styling the Accordion

Finally, we may style our accordion to make it appear more aesthetically pleasing. This may be accomplished by importing a CSS file into our Accordion.js code and inserting it there.

import './Accordion.css';

Accordion.css

/* Accordion.css */
button {
   padding: 8px 20px;
   background-color: #4CAF50;
   color: white;
   border: none;
   cursor: pointer;
   margin-right: 10px;
}
p {
   font-size: 20px;
   margin-top: 20px;
}

This will give our accordion some basic styling, such as a green background colour for the button's accordion background and white text with a cursor change to indicate that the button can be clicked. To make the buttons more dynamic, you can also add the states of hover, activity, and attention.

/* Accordion.css */
button:hover {
   background-color: #3e8e41;
}
button:active {
   transform: scale(0.95);
}
button:focus {
   outline: none;
}

By selecting the close all button, the user can close every element of the accordion, giving it more dynamic functionality. Additionally, you can include a feature that lets users to access all of the accordion items by clicking a "open all" button.

To enable the user to close and open all the accordion items, two new buttons, "Close All" and "Open All," as well as two new event handlers, "handleClose All" and "handleOpen All," have been added to this code.

Step 5: Making the Accordion Responsive

Using CSS media queries, we can style the component differently depending on the size of the screen to make the accordion responsive. When the screen width is less than 500px, for instance, we can alter the font size of the content of the accordion.

/* Accordion.css */
@media screen and (max-width: 500px) {
   p {
      font-size: 16px;
   }
}

We can also use flexbox to make the component take up the full width of its container on small screens.

/* App.css */
.accordion-container {
   display: flex;
   flex-wrap: wrap;
   justify-content: center;
}

After following these instructions, your ReactJS application should have a responsive and fully functional accordion. This accordion can be further expanded upon and altered to meet the unique requirements of your application. But bear in mind that there are a variety of additional approaches to accomplish the same goal when building an accordion with ReactJS.

To ensure that the active accordion item remains visible even after a page refresh, you might also include the option to save it in local storage. To make the accordion more visually pleasing, you may also include the capability to animate the accordion elements when they are opened and closed.

Output

Conclusion

Using the provided sample code, you should be able to create a basic accordion that may later be enhanced to match the specific needs of your application. Just bear in mind that there are many other methods to use ReactJS to create an accordion and achieve the same result. By following the instructions in this blog post, you can create an accordion that can be helpful for organizing and displaying material in your ReactJS application.

Updated on: 06-Mar-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements