On this article, we’ll harness the complete capabilities of React.js to create an accordion element — a consumer interface system that’s regularly utilized in net and cell functions 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.
Undertaking Setup
We’ll be utilizing React.js to create our accordion element. To make use of React.js, we’ll have to 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 elsewhere if you happen to 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.
Now if we test our undertaking 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.
Observe: if you happen to’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’ll be able to 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 component that’s wrapped within the <div>
component with a category title of App
, so we now have an empty <div>
component. Then open App.css
and index.css
and delete the contents of each information. (In case 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>
component 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 element known as AccordionItem
. Contained in the return
key phrase, we’ll create a heading component with “Accordion” because the content material (<h1>Accordion</h1>
), and beneath that one other element known 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>
component with a category title of container
. We then export the primary Accordion
element. 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 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 information in an array of objects, we make sure that the information is dynamically saved and the accordion element is reusable. Beneath is the accordion information. You may copy and paste it in your AccordionData.js
file instantly:
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 will probably be displayed in our accordion element. The query
property incorporates the query or header textual content, whereas the reply
property incorporates the reply or content material that seems when the query is clicked or expanded. Ensure to import the element within the Accordion.js
file. That’s all for the AccordionData.js
file.
Accordion Element Format
Let’s create the format of our accordion element.
We first have to put in react-icons
to our undertaking from the npm registry:
npm set up react-icons
We additionally have to 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 will probably be rendered contained in the AccordionItem
element. We’ll move 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 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 normally used to toggle theisOpen
state when the consumer clicks on the merchandise to develop or collapse it.
The AccordionComponent Physique
On the high of the Accordion.js
file, be sure 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" type={
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 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 known as contentHeight
so it may be handed into the ref
attribute of our answer-container
component. We do this so we’ll have the ability to dynamically modify the peak of the container based mostly on the reply content material’s scroll peak.
Let’s break down the code construction.
Button component (
<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 titlequestion-container
. The category title is conditionally set toenergetic
if theisOpen
prop is true, which is used to type the button in a different way when the reply is open.Query content material. The query content material consists of a
<p>
component with a categoryquestion-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 suitable of the query. The category title is conditionally set toenergetic
if theisOpen
prop is true, which can be utilized to rotate or type the arrow in a different way when the reply is open.Reply div. Following the
<button>
, there’s a<div>
component with the category titleanswer-container
. This div has anref
attribute set to thecontentHeight
variable, which permits it to measure itsscrollHeight
. The type attribute is used to dynamically set the peak of this container based mostly on whether or not the merchandise is open or closed. WhenisOpen
is true, it’ll have a peak equal to its content material’sscrollHeight
, making the reply seen. WhenisOpen
is fake, it has a peak of0px
, hiding the reply content material.Reply content material. The reply content material consists of a
<p>
component with classanswer-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 type our accordion element. 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;
high: 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.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: peak .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 fundamental functionalities of our accordion element. We do this inside the primary Accordion
element.
Primary accordion element construction
The code under 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'>
{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 element is to create the accordion-style interface that shows a listing of things, every consisting of a query and its corresponding reply. The consumer 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 chunk of element state utilizing theuseState
hook.activeIndex
represents the index of the at the moment energetic (open) accordion merchandise, ornull
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 anindex
parameter, which represents the index of the merchandise that was clicked.Contained in the perform,
setActiveIndex
is known as with a perform that toggles theactiveIndex
state. If the clicked merchandise’s index (index
) matches the present energetic index (prevIndex
), it unitsactiveIndex
tonull
, successfully closing the merchandise. In the event that they don’t match, it unitsactiveIndex
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 element returns JSX that defines the construction of the accordion interface. The outermost<div>
with the category titlecontainer
is the container for all accordion objects.{information.map((merchandise, index) => ( ... ))}
. This code maps over an array known asinformation
that’s retrieved from theAccordionData.js
file. For every merchandise within theinformation
array, it renders anAccordionItem
element. Thekey
prop is ready toindex
to make sure every merchandise has a singular key for React’s rendering optimization.The
query
,reply
,isOpen
, andonClick
props are handed to theAccordionItem
element. Thequery
andreply
props include the textual content to be displayed for every merchandise. TheisOpen
prop is ready totrue
if the merchandise’s index matches the at the moment energetic index (indicating that it ought to be open), and theonClick
prop is a callback perform that triggers thehandleItemClick
perform when the merchandise is clicked.export default Accordion;
. This line exports theAccordion
element in order that it may be imported and utilized in different components of our utility. We have now beforehand rendered the element in ourApp.js
file.
In abstract, the Accordion
element manages the state of the at the moment energetic accordion merchandise and makes use of this state to regulate the opening and shutting conduct. It dynamically generates a listing of AccordionItem
elements 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 an exquisite and totally practical accordion element! 🥳 🎉 The entire supply code for this tutorial is on the market on CodeSandbox.
Conclusion
On this article, we’ve checked out the best way to make the most of React.js to create a dynamic and user-friendly accordion element. Accordions are a standard consumer interface component for neatly organizing and displaying content material.
We started by making a React undertaking, organizing the element, 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 coated the idea of storing the accordion information in one other file.
Hopefully you now have a strong understanding of the best way to develop a feature-rich accordion element with React.js. Comfortable coding!