Monday, April 8, 2024

Construct an Accordion Part with React.js — SitePoint

Must read

On this article, we’ll harness the complete capabilities of React.js to create an accordion element — a person interface machine that’s steadily utilized in internet and cellular purposes to rearrange and present content material in a user-friendly and space-efficient method.

To get essentially the most our of this text, you’ll want the next:

The next video exhibits our completed accordion element.

Desk of Contents

Mission Setup

We’ll be utilizing React.js to create our accordion element. To make use of React.js, we’ll must create a React surroundings, and we’ll do this by way of a command immediate.

Open your terminal software and navigate to the desktop (or someplace else for those who want). Then run the next command to create your React app:

npx create-react-app accordion-component

As soon as the packages are put in, we’ll see one thing just like the picture beneath.

Now if we examine our venture folder, we’ll discover a folder named /accordion-component/ with all of the packages put in.

Folder Construction

Open the brand new /accordion-component/ folder in a code editor. Additionally open the React software within the browser. We will do this by way of the inbuilt terminal in our code editor by typing the command npm run begin to run the applying on the browser.

Be aware: for those who’re utilizing Visible Studio, you should use the shortcut (ctrl + shift + `) to open up the terminal. In case your code editor doesn’t have the function of an inbuilt terminal, you’ll be able to simply run instructions within the command immediate app.)

Let’s subsequent edit the pointless recordsdata and code blocks that can hinder the execution of our software. Firstly, open App.js and take away the entire header aspect that’s wrapped within the <div> aspect with a category title of App, so we now have an empty <div> aspect. Then open App.css and index.css and delete the contents of each recordsdata. (In the event you view the online web page as soon as extra, you’ll see that it’s now clean, which is simply what we would like for now.)

Subsequent, let’s create a brand new folder referred to as /AccordionComponent/ beneath the /src/ folder listing. Contained in the /AccordionComponent/ folder, create a file referred to as Accordion.js for the elements and one other file named AccordionData.js to retailer the textual content for use for our accordion. Then go to the App.js file and import the Accordion.js file. After the file has been imported, we render it contained in the <div> aspect like so:

import './App.css';
import Accordion from './AccordionComponent/Accordion';

operate App() {
 return (
  <div className="App">
   <Accordion />

export default App;

After that’s accomplished, go to the Accordion.js file and create a element referred to as AccordionItem. Contained in the return key phrase, we’ll create a heading aspect with “Accordion” because the content material (<h1>Accordion</h1>), and beneath that one other element referred to as Accordion. After doing that, we’ll render our AccordionItem element inside that of the primary Accordion, ensuring the rendered element is wrapped in a <div> aspect with a category title of container. We then export the primary Accordion element. Now we now have one thing like this:

import React from 'react';

const AccordionItem = () => {

const Accordion = () => {
 return (
    <AccordionItem />

export default Accordion;

If we view our internet web page, we’ll see our heading on the display.

We’ll subsequent create an array of objects containing the questions and solutions textual content contained in the AccordionData.js file. By storing our accordion knowledge in an array of objects, we make sure that the information is dynamically saved and the accordion element is reusable. Beneath is the accordion knowledge. You may copy and paste it in your AccordionData.js file immediately:

const knowledge = [
   question: 'What are accordion components?',
   answer: 'Accordion components are user interface elements used for organizing and presenting content in a collapsible manner. They typically consist of a header, content, and an expand/collapse action.' ,
   question: 'What are they used for?',
   answer: 'They are commonly employed in various contexts, including FAQs, product descriptions, navigation menus, settings panels, and data tables, to save screen space and provide a structured and user-friendly interface for presenting information or options.',
   question: 'Accordion as a musical instrument',
   answer: 'The accordion is a musical instrument with a keyboard and bellows. It produces sound by air passing over reeds when the player expands or compresses the bellows, used in various music genres.',
   question: 'Can I create an accordion component with a different framework?',
   answer: 'Yes of course, it is very possible to create an accordion component with another framework.',

 export default knowledge;

Within the code above, we now have an array of objects holding the information that can be displayed in our accordion element. The query property accommodates the query or header textual content, whereas the reply property accommodates the reply or content material that seems when the query is clicked or expanded. Be certain to import the element within the Accordion.js file. That’s all for the AccordionData.js file.

Accordion Part Structure

Let’s create the structure of our accordion element.

We first have to put in react-icons to our venture from the npm registry:

npm set up react-icons

We additionally must import useState and useRef hooks. We will do this by pasting this into the highest of the file:

import React, { useRef, useState } from 'react'

The HTML construction can be rendered contained in the AccordionItem element. We’ll cross 4 props into the AccordionItem element: query, reply, isOpen, and onClick.

Let’s break down the props to see what they’ll be wanted for:

  • query. This prop represents the textual content or content material for the query a part of the accordion merchandise.
  • reply. This prop represents the textual content or content material for the reply a part of the accordion merchandise.
  • isOpen. This prop is a Boolean that signifies whether or not the accordion merchandise is presently open (expanded) or closed (collapsed). It controls whether or not the reply content material is seen or hidden.
  • onClick. This prop is a callback operate that will get executed when the person interacts with the accordion merchandise. It’s often used to toggle the isOpen state when the person clicks on the merchandise to increase or collapse it.

The AccordionComponent Physique

On the high of the Accordion.js file, ensure to import the arrow icon from the react-icons bundle, like this:

import { RiArrowDropDownLine } from 'react-icons/ri'

This would be the construction of a single accordion merchandise:

const AccordionItem = ({ query, reply, isOpen, onClick }) => {
 const contentHeight = useRef()
    <div className="wrapper" >
    <button className={`question-container ${isOpen ? 'energetic' : ''}`} onClick={onClick} >
     <p className='question-content'>{query}</p>
     <RiArrowDropDownLine className={`arrow ${isOpen ? 'energetic' : ''}`} /> 

     <div ref={contentHeight} className="answer-container" model={
          ? { top: contentHeight.present.scrollHeight }
          : { top: "0px" }
      <p className="answer-content">{reply}</p>

On this code snippet, the accordion merchandise sits inside a mum or dad <div> with a category title wrapper. This construction permits for displaying a query and its reply in a collapsible method.

We retailer our useRef hook in a variable referred to as contentHeight so it may be handed into the ref attribute of our answer-container aspect. We do this so we’ll have the ability to dynamically regulate the peak of the container primarily based on the reply content material’s scroll top.

Let’s break down the code construction.

  • Button aspect (<button>). That is the interactive a part of the accordion merchandise that customers click on to toggle the reply’s visibility. It has a category title question-container. The category title is conditionally set to energetic if the isOpen prop is true, which is used to model the button otherwise when the reply is open.

  • Query content material. The query content material consists of a <p> aspect with a category question-content. The textual content for the query is taken from the query prop.

  • Arrow Icon (<RiArrowDropDownLine />). An arrow icon used for toggling is exhibited to the proper of the query. The category title is conditionally set to energetic if the isOpen prop is true, which can be utilized to rotate or model the arrow otherwise when the reply is open.

  • Reply div. Following the <button>, there’s a <div> aspect with the category title answer-container. This div has an ref attribute set to the contentHeight variable, which permits it to measure its scrollHeight. The model attribute is used to dynamically set the peak of this container primarily based on whether or not the merchandise is open or closed. When isOpen is true, it should have a top equal to its content material’s scrollHeight, making the reply seen. When isOpen is fake, it has a top of 0px, hiding the reply content material.

  • Reply content material. The reply content material consists of a <p> aspect with class answer-content. The textual content for the reply is taken from the reply prop.

Styling our Accordion Part

Now that we’re accomplished with the markup, let’s model our accordion element. The styling will be discovered within the code block beneath:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;

physique {
  background-color: #f2f2f2;

.container {
  max-width: 650px;
  width: 100%;
  place: absolute;
  high: 50%;
  left: 50%;
  remodel: translate(-50%, -50%);

.wrapper {
  border-bottom: 1px stable black;
  overflow: hidden;

.wrapper .question-container {
  width: 100%;
  text-align: left;
  padding: 20px 10px;
  show: flex;
  align-items: heart;
  justify-content: space-between;
  font-weight: 500;
  font-size: 20px;
  background: clear;
  border: none;
  cursor: pointer;

.question-container.energetic {
  colour: #1db954;
  background-image: linear-gradient(90deg,clear,rgba(0,0,0,0.04),clear);

.wrapper .question-container:hover {
  background-image: linear-gradient(90deg,clear,rgba(0,0,0,0.04),clear);

.wrapper .arrow {
  font-size: 2rem;
  transition: .5s ease-in-out;

.arrow.energetic {
  rotate: 180deg;
  colour: #1db954;

.wrapper .answer-container {
  padding: 0 1rem;
  transition: top .7s ease-in-out;

.wrapper .answer-content {
  padding: 1rem 0;
  font-size: 20px;
  font-style: italic;

Because of the styling above, we now have the define of our accordionItem. Now let’s import the information from our AccordionData file and declare the essential functionalities of our accordion element. We do this inside the primary Accordion element.

Predominant accordion element construction

The code beneath defines the practical element named Accordion:

const Accordion = () => {
 const [activeIndex, setActiveIndex] = useState(null);

 const handleItemClick = (index) => {
  setActiveIndex((prevIndex) => (prevIndex === index ? null : index));

 return (
  <div className='container'>
    {, index) => (
     isOpen={activeIndex === index}
     onClick={() => handleItemClick(index)}

export default Accordion;

The aim of this element is to create the accordion-style interface that shows an inventory of things, every consisting of a query and its corresponding reply. The person can click on on a query to increase or collapse its reply. Let’s break down the code step-by-step.

  • const [activeIndex, setActiveIndex] = useState(null);. This line units a bit of element state utilizing the useState hook. activeIndex represents the index of the presently energetic (open) accordion merchandise, or null if no merchandise is open. setActiveIndex is the operate used to replace this state.

  • const handleItemClick = (index) => { ... }. ThehandleItemClick operate is answerable for dealing with clicks on accordion gadgets. It takes an index parameter, which represents the index of the merchandise that was clicked.

    Contained in the operate, setActiveIndex is named with a operate that toggles the activeIndex state. If the clicked merchandise’s index (index) matches the present energetic index (prevIndex), it units activeIndex to null, successfully closing the merchandise. In the event that they don’t match, it units activeIndex to the clicked merchandise’s index, opening it.

    This strategy ensures that just one accordion merchandise will be opened at a time, as a result of if we open one accordion merchandise, it closes any beforehand opened accordion merchandise.

  • The return assertion. This element returns JSX that defines the construction of the accordion interface. The outermost <div> with the category title container is the container for all accordion gadgets.

  • {, index) => ( ... ))}. This code maps over an array referred to as knowledge that’s retrieved from the AccordionData.js file. For every merchandise within the knowledge array, it renders an AccordionItem element. The key prop is about to index to make sure every merchandise has a novel key for React’s rendering optimization.

    The query, reply, isOpen, and onClick props are handed to the AccordionItem element. The query and reply props include the textual content to be displayed for every merchandise. The isOpen prop is about to true if the merchandise’s index matches the presently energetic index (indicating that it must be open), and the onClick prop is a callback operate that triggers the handleItemClick operate when the merchandise is clicked.

  • export default Accordion;. This line exports the Accordion element in order that it may be imported and utilized in different elements of our software. We’ve beforehand rendered the element in our App.js file.

In abstract, the Accordion element manages the state of the presently energetic accordion merchandise and makes use of this state to manage the opening and shutting habits. It dynamically generates an inventory of AccordionItem elements primarily based on the information obtained, permitting customers to work together with the accordion interface by clicking on every of the inquiries to reveal or conceal their solutions.

Our Completed Product

We now have an exquisite and absolutely practical accordion element! 🥳 🎉 The whole supply code for this tutorial is obtainable on CodeSandbox.


On this article, we’ve checked out the way to make the most of React.js to create a dynamic and user-friendly accordion element. Accordions are a typical person interface aspect for neatly organizing and displaying content material.

We started by making a React venture, organizing the element, and styling it for a completed look. We went into the interior workings of the system, together with state administration and coping with person interactions. As well as, for scalability and reusability, we coated the idea of storing the accordion knowledge in one other file.

Hopefully you now have a stable understanding of the way to develop a feature-rich accordion element with React.js. Completely satisfied coding!

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article