Home Programming Methods to Construct an Accordion Element with React.js — SitePoint

Methods to Construct an Accordion Element with React.js — SitePoint

0
Methods to Construct an Accordion Element with React.js — SitePoint

[ad_1]

On this article, we’ll harness the complete capabilities of React.js to create an accordion part — a person interface machine that’s steadily 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

Undertaking Setup

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

Open your terminal software and navigate to the desktop (or some place else when 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 examine 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 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 appliance on the browser.

Be aware: when 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 characteristic of an inbuilt terminal, you may 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/ 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 executed, 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 title of container. We then export the primary Accordion part. Now we now have 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 screen.

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. Beneath is the accordion knowledge. You’ll be able to 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 info that will probably 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. Make certain 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 will do this by pasting this into the highest of the file:

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

The HTML construction will probably be rendered contained in the AccordionItem part. We’ll go 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 present 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 person interacts with the accordion merchandise. It’s often used to toggle the isOpen state when the person clicks on the merchandise to develop or collapse it.

The AccordionComponent Physique

On the high of the Accordion.js file, be certain that to import the arrow icon from the react-icons package deal, 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 ? 'energetic' : ''}`} onClick={onClick} >
     <p className='question-content'>{query}</p>
     <RiArrowDropDownLine className={`arrow ${isOpen ? 'energetic' : ''}`} /> 
    </button>

     <div ref={contentHeight} className="answer-container" fashion={
          isOpen
          ? { top: contentHeight.present.scrollHeight }
          : { top: "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 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 alter the peak of the container based mostly 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 fashion 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 precise of the query. The category title is conditionally set to energetic if the isOpen prop is true, which can be utilized to rotate or fashion 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 fashion 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’ll 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 Element

Now that we’re executed with the markup, let’s fashion our accordion part. The styling might 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;
}

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 essential functionalities of our accordion part. We do this inside the primary Accordion part.

Principal 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 a listing of things, every consisting of a query and its corresponding reply. The person can click on on a query to develop 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 present energetic (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 chargeable 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 is known as with a perform 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 method ensures that just one accordion merchandise might 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 title container is the container for all accordion objects.

  • {knowledge.map((merchandise, 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 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 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 present energetic index (indicating that it ought to 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 elements of our software. We’ve beforehand rendered the part in our App.js file.

In abstract, the Accordion part manages the state of the at present energetic accordion merchandise and makes use of this state to manage the opening and shutting conduct. It dynamically generates a listing of AccordionItem parts based mostly on the info obtained, permitting customers to work together with the accordion interface by clicking on every of the inquiries to reveal or disguise their solutions.

Our Completed Product

We now have an attractive and absolutely purposeful accordion part! 🥳 🎉 The entire supply code for this tutorial is offered on CodeSandbox.

Conclusion

On this article, we’ve checked out methods to make the most of React.js to create a dynamic and user-friendly accordion part. Accordions are a typical person 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 person interactions. As well as, for scalability and reusability, we lined the idea of storing the accordion knowledge in one other file.

Hopefully you now have a stable understanding of methods to develop a feature-rich accordion part with React.js. Comfortable coding!

[ad_2]

Supply hyperlink

LEAVE A REPLY

Please enter your comment!
Please enter your name here