how to create accordion in react js?
March 21, 2023Hi Friends π,
Welcome To aGuideHub!
To create accordion in React js, you have to use accordion css
which I have protected in the below example.
Today, I am going to show you, how to create accordion in react js.
Table of contents
- Display Accordian Header based on State value.
- Add onClick event to Accordian header.
Letβs start with the first step.
Step 1: Display Accordian Header based on State value.
We need to show state then the user clicked on the accordion. you have to toggle show state that how you can create accordion in react js.
<div>Accordion Header</div>
<div className="sign">{show ? '-' : '+'}</div>
Step 2: Add onClick event to Accordian header.
To achieve accordion functionality, we will create a JS function to toggle the show
state value between true and false.
const handleOpen = () => {
setShow(!show); // Toggle accordion
};
ReactJS create accordion example.
The below code is an example of the previously declared function will be added as an onClick
event for the accordion header. Hence, the visibility of the accordion body is toggled when the header is clicked.
App.js
import React, { useState } from "react";
import "./App.css";
export default function App() {
// State to show/hide accordion
const [show, setShow] = useState(false);
const handleOpen = () => {
setShow(!show); // Toggle accordion
};
return (
<div className="app">
<div className="accordian">
<div className="accordian-header" onClick={handleOpen}>
<div>Accordion Header</div>
<div className="sign">{show ? '-' : '+'}</div>
</div>
{show && (
<div className="accordian-body">
Lorem Ipsum is simply dummy text of the printing and type setting
industry. Lorem Ipsum has been the industry's ever since the 1500s,
when an unknown printer took a galley of type standard dummy text
and scrambled it to make a type specimen book.
</div>
)}
</div>
</div>
);
}
App.CSS
.app {
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
flex-direction: column;
gap: 20px;
}
.sign {
font-size: 25px;
}
.accordian {
width: 300px;
border: 1px solid rgb(133, 133, 133);
}
.accordian-header {
font-weight: 600;
font-size: 18px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px 15px;
border: 2px solid rgb(133, 133, 133);
background-color: rgb(255, 255, 143);
}
.accordian-body {
padding: 15px 5px;
}
Check the output of the above code example.
Here, we are provided code sandbox links for the above program create accordion in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best π