-2.7 C
New York
Monday, January 15, 2024

How one can Construct an Accordion Element with React.js — SitePoint


On this article, we’ll harness the total capabilities of React.js to create an accordion part — a consumer interface gadget that’s ceaselessly utilized in net and cell purposes to rearrange and present content material in a user-friendly and space-efficient manner.

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 surroundings, and we’ll do this by way of a command immediate.

Open your terminal utility and navigate to the desktop (or someplace else in the event 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 under.

What we see in the terminal once our app is created

Now if we verify our mission 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 are able to 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.

Word: in the event you’re utilizing Visible Studio, you need to 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 possibly can simply run instructions within the command immediate app.)

Let’s subsequent edit the pointless recordsdata and code blocks that may 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 recordsdata. (Should you view the online web page as soon as extra, you’ll see that it’s now clean, which is simply what we wish for now.)

Subsequent, let’s create a brand new folder referred to as /AccordionComponent/ below the /src/ folder listing. Contained in the /AccordionComponent/ folder, create a file referred to as Accordion.js for the parts 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';

perform App() {
 return (
  <div className="App">
   <Accordion />
  </div>
 );
}

export default App;

After that’s finished, go to the Accordion.js file and create a part 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 part referred to as Accordion. After doing that, we’ll render our AccordionItem part inside that of the primary Accordion, ensuring the rendered part is wrapped in a <div> aspect with a category identify of container. We then export the primary 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 information in an array of objects, we make sure that the information is dynamically saved and the accordion part is reusable. Under is the accordion information. You’ll be able to copy and paste it in your AccordionData.js file straight:

const information = [
  {
   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 information;

Within the code above, we’ve an array of objects holding the information that shall be displayed in our accordion part. 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. Ensure that to import the part within the Accordion.js file. That’s all for the AccordionData.js file.

Accordion Element Format

Let’s create the structure of our accordion part.

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

npm set up react-icons

We additionally must import useState and useRef hooks. We are able to do 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 cross 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 at the moment open (expanded) or closed (collapsed). It controls whether or not the reply content material is seen or hidden.
  • onClick. This prop is a callback perform that will get executed when the consumer interacts with the accordion merchandise. It’s often used to toggle the isOpen state when the consumer clicks on the merchandise to broaden or collapse it.

The AccordionComponent Physique

On the prime of the Accordion.js file, be sure 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 mother or father <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 referred to as contentHeight so it may be handed into the ref attribute of our answer-container aspect. We do this so we’ll be capable of dynamically alter the peak of the container based mostly 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 correct 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 based mostly on whether or not the merchandise is open or closed. When isOpen is true, it can 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 Element

Now that we’re finished with the markup, let’s model our accordion part. The styling could be discovered within the code block under:

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

physique {
  background-color: #f2f2f2;
}

.container {
  max-width: 650px;
  width: 100%;
  place: absolute;
  prime: 50%;
  left: 50%;
  remodel: 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 {
  shade: #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;
  shade: #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 information from our AccordionData file and declare the essential functionalities of our accordion part. We do this inside the primary Accordion part.

Primary accordion part construction

The code under defines the useful part named Accordion:

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

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

 return (
  <div className='container'>
    {information.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 consumer 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 bit of part state utilizing the useState hook. activeIndex represents the index of the at the moment lively (open) accordion merchandise, or null if no merchandise is open. setActiveIndex is the perform used to replace this state.

  • const handleItemClick = (index) => { ... }. ThehandleItemClick perform is accountable 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 perform, setActiveIndex known as with a perform 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 strategy 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.

  • {information.map((merchandise, index) => ( ... ))}. This code maps over an array referred to as information that’s retrieved from the AccordionData.js file. For every merchandise within the information array, it renders an AccordionItem part. The key prop is ready 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 part. The query and reply props include the textual content to be displayed for every merchandise. The isOpen prop is ready to true if the merchandise’s index matches the at the moment lively index (indicating that it must be open), and the onClick prop is a callback perform that triggers the handleItemClick perform 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 components of our utility. We now have beforehand rendered the part in our App.js file.

In abstract, the Accordion part manages the state of the at the moment lively accordion merchandise and makes use of this state to regulate the opening and shutting conduct. It dynamically generates an inventory of AccordionItem parts based mostly on the information 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 stupendous and totally useful accordion part! 🥳 🎉 The entire supply code for this tutorial is on the market on CodeSandbox.

Conclusion

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

We started by making a React mission, organizing the part, and styling it for a completed look. We went into the inside workings of the system, together with state administration and coping with consumer interactions. As well as, for scalability and reusability, we lined the idea of storing the accordion information in one other file.

Hopefully you now have a strong understanding of the right way to develop a feature-rich accordion part with React.js. Comfortable coding!



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles