Sunday, March 3, 2024

The way to Construct an Accordion Part with React.js — SitePoint


On this article, we’ll harness the total capabilities of React.js to create an accordion part — a person interface machine that’s regularly utilized in net and cellular purposes to rearrange and present content material in a user-friendly and space-efficient means.

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

The next video reveals our completed accordion part.

Desk of Contents

Mission Setup

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

Open your terminal utility and navigate to the desktop (or some other place in case you choose). 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.

What we see in the terminal once our app is created

Now if we test our challenge 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 utility within the browser. We will try this by way of the inbuilt terminal in our code editor by typing the command npm run begin to run the appliance on the browser.

Word: in case you’re utilizing Visible Studio, you should utilize the shortcut (ctrl + shift + `) to open up the terminal. In case your code editor doesn’t have the function of an inbuilt terminal, you may simply run instructions within the command immediate app.)

Let’s subsequent edit the pointless information and code blocks that can hinder the execution of our utility. Firstly, open App.js and take away the entire header aspect that’s wrapped within the <div> aspect with a category identify of App, so we now have an empty <div> aspect. Then open App.css and index.css and delete the contents of each information. (When you view the net 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 known as /AccordionComponent/ beneath the /src/ folder listing. Contained in the /AccordionComponent/ folder, create a file known 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 />
  </div>
 );
}

export default App;

After that’s carried out, go to the Accordion.js file and create a part known 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 part known as Accordion. After doing that, we’ll render our AccordionItem part inside that of the principle Accordion, ensuring the rendered part is wrapped in a <div> aspect with a category identify of container. We then export the principle Accordion part. Now we’ve one thing like this:

import React from 'react';


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


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

export default Accordion;

If we view our net 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 info is dynamically saved and the accordion part is reusable. Under is the accordion knowledge. You’ll be able to copy and paste it in your AccordionData.js file straight:

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’ve an array of objects holding the info that shall be displayed in our accordion part. The query property comprises the query or header textual content, whereas the reply property comprises the reply or content material that seems when the query is clicked or expanded. Make sure that to import the part within the Accordion.js file. That’s all for the AccordionData.js file.

Accordion Part Structure

Let’s create the structure of our accordion part.

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

npm set up react-icons

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

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

The HTML construction shall be rendered contained in the AccordionItem part. We’ll move 4 props into the AccordionItem part: 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 broaden or collapse it.

The AccordionComponent Physique

On the prime 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()
  return(
    <div className="wrapper" >
    <button className={`question-container ${isOpen ? 'lively' : ''}`} onClick={onClick} >
     <p className='question-content'>{query}</p>
     <RiArrowDropDownLine className={`arrow ${isOpen ? 'lively' : ''}`} /> 
    </button>

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

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

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

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 identify question-container. The category identify is conditionally set to lively if the isOpen prop is true, which is used to model the button in another way 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 appropriate of the query. The category identify is conditionally set to lively if the isOpen prop is true, which can be utilized to rotate or model the arrow in another way when the reply is open.

  • Reply div. Following the <button>, there’s a <div> aspect with the category identify 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 peak equal to its content material’s scrollHeight, making the reply seen. When isOpen is fake, it has a peak 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 carried out with the markup, let’s model our accordion part. The styling could 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;
  prime: 50%;
  left: 50%;
  rework: translate(-50%, -50%);
}

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

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

.question-container.lively {
  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.lively {
  rotate: 180deg;
  colour: #1db954;
}

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

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

On account of the styling above, we now have the define of our accordionItem. Now let’s import the info from our AccordionData file and declare the fundamental functionalities of our accordion part. We try this inside the principle Accordion part.

Foremost accordion part construction

The code beneath defines the purposeful part named Accordion:

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

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

 return (
  <div className='container'>
    {knowledge.map((merchandise, index) => (
    <AccordionItem
     key={index}
     query={merchandise.query}
     reply={merchandise.reply}
     isOpen={activeIndex === index}
     onClick={() => handleItemClick(index)}
    />
   ))}
  </div>
 )
};

export default Accordion;

The aim of this part 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 broaden or collapse its reply. Let’s break down the code step-by-step.

  • const [activeIndex, setActiveIndex] = useState(null);. This line units a chunk of part state utilizing the useState hook. activeIndex represents the index of the presently lively (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 objects. 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 lively 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 method ensures that just one accordion merchandise could 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 part returns JSX that defines the construction of the accordion interface. The outermost <div> with the category identify container is the container for all accordion objects.

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

    The query, reply, isOpen, and onClick props are handed to the AccordionItem part. The query and reply props comprise the textual content to be displayed for every merchandise. The isOpen prop is ready to true if the merchandise’s index matches the presently lively index (indicating that it ought to 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 part in order that it may be imported and utilized in different elements of our utility. Now we have beforehand rendered the part in our App.js file.

In abstract, the Accordion part manages the state of the presently lively 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 info obtained, permitting customers to work together with the accordion interface by clicking on every of the inquiries to reveal or cover their solutions.

Our Completed Product

We now have a phenomenal and totally purposeful accordion part! 🥳 🎉 The entire supply code for this tutorial is obtainable on CodeSandbox.

Conclusion

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

We started by making a React challenge, organizing the part, and styling it for a completed look. We went into the internal 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 strong understanding of how you can develop a feature-rich accordion part with React.js. Joyful coding!



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles