How to Create Accordion in React

In this article, We will learn how to create Accordion in React with proper examples. This comprehensive guide provides you with step-by-step instructions and real-life examples of Accordion which you can use for your project.

So let’s start first if you don’t know what is Accordion.

 

Create Accordion in React

 

What is Accordion?

 

Accordion which is also known as an accordion is a UI component that expands and collapses content sections based on user clicks. There are two types of accordions: single-click accordion where only one section expands on click at a time, and multi-click accordion where multiple sections can be expanded on user click.

 

Create Accordion in React

 

Follow the below steps to create an accordion in React.

 

Step 1.

In your React project, create a new component for the accordion. You can name it Accordion.js or any other suitable name. Now copy the below code in your accordion.js file –

import React, { useState } from 'react';
import './Accordion.css'; // Import CSS for styling

const Accordion = ({ sections }) => {
  const [expandedSection, setExpandedSection] = useState(null);

  const toggleSection = (sectionIndex) => {
    if (expandedSection === sectionIndex) {
      setExpandedSection(null); // Collapse section if already expanded
    } else {
      setExpandedSection(sectionIndex); // Expand section
    }
  };

  return (
    <div className="accordion">
      {sections.map((section, index) => (
        <div key={index} className="accordion-section">
          <div
            className={`accordion-header ${expandedSection === index ? 'expanded' : ''}`}
            onClick={() => toggleSection(index)}
          >
            {section.header}
          </div>
          {expandedSection === index && (
            <div className="accordion-content">
              {section.content}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default Accordion;


In this Accordion component, I have passed an array of sections as props from the main App.js to this Accordion component. The sections array has header and content properties when the user clicks on the header the toogleSection method triggers and toggles the accordion.

 

Steps 2:

This is an optional step for this example here I have imported styling for my accordion component using the Accordion.css. Create an Accordion.css file and copy and paste the below CSS you can change the same according to your requirements –

/* Accordion Container */
.accordion {
border: 1px solid #ccc;
border-radius: 4px;
width: 75%;
}

/* Accordion Section */
.accordion-section {
border-bottom: 1px solid #ccc;
}

/* Accordion Header */
.accordion-header {
padding: 10px;
cursor: pointer;
background-color: #f0f0f0;
font-weight: bold;
transition: background-color 0.3s ease; /* Smooth transition for background color */
}

/* Expanded Accordion Header */
.accordion-header.expanded {
background-color: #e0e0e0; /* Change background color when expanded */
}

/* Accordion Content */
.accordion-content {
padding: 10px;
background-color: #fff;
transition: max-height 0.3s ease; /* Smooth transition for max-height */
overflow: hidden; /* Hide overflow content */
}

/* Expanded Accordion Content */
.accordion-section.expanded .accordion-content {
max-height: 1000px; /* Adjust max-height for expanded content */
}

 

Steps 3:

This is the final step here in our main App.js file we’ve created an array named sections with 5 objects, each representing a section of the accordion. Each object contains header and content properties. We then pass this array as a prop to the Accordion component created in step 1.

Copy and paste the below code in the App.js file.

import React from 'react';
import Accordion from './Accordion'; // Import Accordion component

const App = () => {
  // Define sections array with 5 sections
  const sections = [
    { header: 'Section 1', content: 'Content for Section 1' },
    { header: 'Section 2', content: 'Content for Section 2' },
    { header: 'Section 3', content: 'Content for Section 3' },
    { header: 'Section 4', content: 'Content for Section 4' },
    { header: 'Section 5', content: 'Content for Section 5' }
  ];

  return (
    <div className="accordion-main">
      <h1>Accordion Example</h1>
      <Accordion sections={sections} />
    </div>
  );
};

export default App;


 

Output-

How to create Accordion in React

This is how you can create an Accordion in React this is the single select accordion only one section will open at a time what if you want to open multiple sections at a time?

 

Create Multi-Select Accordion in React

 

Unlike traditional single-select accordions where only one section can be expanded at a time, the multi-select accordion provides the flexibility for users to expand multiple sections based on their preferences.

To create a multi-select accordion I made some changes to the Accordion component below is the code –

 

import React, { useState } from 'react';
import './Accordion.css'; // Import CSS for styling

const Accordion = ({ sections }) => {
  const [expandedSections, setExpandedSections] = useState([]);

  const toggleSection = (sectionIndex) => {
    if (expandedSections.includes(sectionIndex)) {
      // If section is already expanded, collapse it
      setExpandedSections(expandedSections.filter(index => index !== sectionIndex));
    } else {
      // If section is not expanded, expand it
      setExpandedSections([...expandedSections, sectionIndex]);
    }
  };                  

  return (
    <div className="accordion">
      {sections.map((section, index) => (
        <div key={index} className="accordion-section">
          <div
            className={`accordion-header ${expandedSections.includes(index) ? 'expanded' : ''}`}
            onClick={() => toggleSection(index)}
          >
            {section.header}
          </div>
          {expandedSections.includes(index) && (
            <div className="accordion-content">
              {section.content}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default Accordion;


 

Output –

Multi Select Accordion in React

The functionality is implemented by modifying the state management logic of the accordion component. Instead of using a single state variable to track the expanded section an array is used to keep track of the indices of all expanded sections.

When a user clicks on a section to expand it, the corresponding index is added to the array of expanded sections. If a section is already expanded and the user clicks on it again, the index is removed from the array, effectively collapsing that section.

This allows users to expand and collapse multiple sections independently, providing a more flexible user Interface.

 

Conclusion

This is how you can create Accordion in React to create dynamic, user-friendly components that enhance engagement and usability. By following the steps outlined in this guide now you can create Accordion and integrate it into your react Component.