Enable Dark Mode!
how-to-create-an-accordion-component-in-react.jpg
By: Alan Joy

How to Create an Accordion Component in React

Technical odoo React

An accordion is a common ui component in React applications; it is used to organise content into expandable sections. This allows users to show or hide information by clicking on the heading. We can find accordions used in FAQs, settings pages, product details, documentation, and many other interfaces. An accordion also helps in keeping the interface compact and allows users to only open and view the sections that they need. This will be very useful when the page contains a lot of information. In this blog, we will build a reusable accordion component using React and Tailwind CSS.

1. What Is an Accordion Component?

An accordion component usually consists of two parts: clickable headings and their content panels. When a user clicks on a heading, its associated content expands. When the user clicks on that heading again, usually the content panel will collapse.

In React, we can manage this accordion behaviour using state. We can store the states of each accordion, and React can render the appropriate content based on the current state.

2. Create a React Project

We can start our tutorial by creating a new Vite React application:

npm create vite@latest react-accordion -- --template react
cd react-accordion
npm install
npm run dev

3. Create a Basic Accordion

Create a new file named Accordion.jsx. We will start by creating a single accordion section.

import { useState } from "react";
export default function Accordion() {
 const [isOpen, setIsOpen] = useState(false);
 return (
   <div className="rounded-lg border">
     <button
       onClick={() => setIsOpen(!isOpen)}
       className="flex w-full justify-between p-4 text-left font-medium"
     >
       What is React?
       <span>{isOpen ? "-" : "+"}</span>
     </button>
     {isOpen && (
       <div className="border-t p-4 text-gray-600">
         React is a JavaScript library for building user interfaces.
       </div>
     )}
   </div>
 );
}

Here, we are using the isOpen state to handle the content visibility. Initially, we set it to false, so the answer will always be hidden at first. When the user clicks the accordion button, we use the setIsOpen method to toggle the state between true and false.

4. Support Multiple Accordion Sections

Now, we can add support for multiple accordion sections in our application. A real application often needs several accordions, like a list of faqs. We can use array data for this case. By using the index of the array, we can manage the states of each accordion section. An array also makes the accordion easier to maintain.

import { useState } from "react";
const items = [
 {
   title: "What is React?",
   content: "React is a JavaScript library for building user interfaces.",
 },
 {
   title: "What are React components?",
   content: "Components are reusable pieces of a React user interface.",
 },
 {
   title: "What is JSX?",
   content: "JSX lets you write HTML-like markup inside JavaScript.",
 },
];
export default function Accordion() {
 const [openIndex, setOpenIndex] = useState(null);
 return (
   <div className="divide-y rounded-lg border">
     {items.map((item, index) => (
       <div key={item.title}>
         <button
           onClick={() =>
             setOpenIndex(openIndex === index ? null : index)
           }
           className="flex w-full justify-between p-4 text-left font-medium"
           aria-expanded={openIndex === index}
         >
           {item.title}
           <span>{openIndex === index ? "-" : "+"}</span>
         </button>
         {openIndex === index && (
           <div className="px-4 pb-4 text-gray-600">
             {item.content}
           </div>
         )}
       </div>
     ))}
   </div>
 );
}

5. Allow Multiple Sections to Stay Open

Sometimes we may want to open several sections of the accordion simultaneously. To enable this behaviour, we need to store all open section indexes in an array instead of only storing a single index. We can update the component with this code to support this behaviour.

const [openIndexes, setOpenIndexes] = useState([]);
const toggleItem = (index) => {
 setOpenIndexes((current) =>
   current.includes(index)
     ? current.filter((item) => item !== index)
     : [...current, index]
 );
};

We also need to update the onClick function of each accordion heading with this.

onClick={() => toggleItem(index)}

And use this isOpen to control the visibility of the accordion content.

const isOpen = openIndexes.includes(index);

The complete code

import { useState } from 'react'
const items = [
 {
   title: 'What is React?',
   content: 'React is a JavaScript library for building user interfaces.',
 },
 {
   title: 'What are React components?',
   content: 'Components are reusable pieces of a React user interface.',
 },
 {
   title: 'What is JSX?',
   content: 'JSX lets you write HTML-like markup inside JavaScript.',
 },
]
export default function Accordion() {
 const [openIndexes, setOpenIndexes] = useState([])
 const toggleItem = (index) => {
   setOpenIndexes((current) =>
     current.includes(index)
       ? current.filter((item) => item !== index)
       : [...current, index],
   )
 }
 return (
   <div className="divide-y rounded-lg border">
     {items.map((item, index) => {
       const isOpen = openIndexes.includes(index)
       return (
         <div key={item.title}>
           <button
             onClick={() => toggleItem(index)}
             className="flex w-full justify-between p-4 text-left font-medium"
             aria-expanded={isOpen}
           >
             {item.title}
             <span>{isOpen ? '-' : '+'}</span>
           </button>
           {isOpen && (
             <div className="px-4 pb-4 text-gray-600">
               {item.content}
             </div>
           )}
         </div>
       )
     })}
   </div>
 )
}

6. Use the Accordion in Your App

To use the accordion in your app, import the accordion component into App.jsx

import Accordion from "./Accordion";
export default function App() {
 return (
   <main className="mx-auto max-w-xl p-6">
     <h1 className="mb-4 text-2xl font-semibold">
       Frequently Asked Questions
     </h1>
     <Accordion />
   </main>
 );
}

We can create a basic accordion component in React using useState and conditional rendering. In this blog, we have begun with creating a single-section accordion, then expanding it to support multiple items, and then adding an option to choose whether one or several sections can remain open in the accordion. Once you have learned the basic behaviour of an accordion, you can add extra features to it, like adding animations, icons, dynamic content, etc according to our application’s needs.

To read more about How to Create a Toast Notification System in React, refer to our blog, How to Create a Toast Notification System in React.


Frequently Asked Questions

What is an accordion component in React?

An accordion is a UI component that allows users to expand and collapse sections to show or hide content.

How do I allow only one accordion section to stay open?

Use a single state variable, such as openIndex, to store the index of the currently open section. Update it whenever a heading is clicked.

Can multiple accordion sections stay open at once?

Yes. Store the indexes of open sections in an array using useState. This allows users to open and close each section independently.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp