To create an accordion using ReactJS functional component, you can follow these steps:
Create a new functional component for your accordion. This component will receive an array of items as props, and it will render each item as a clickable header and a collapsible content section.
Add some CSS styles to your accordion component. You can style the header and content sections as you prefer, and I am using tailwindcss.
Use the accordion component in your app by passing an array of items as props.
import React, { useState } from "react";
function Accordion({ items }) {
const [activeIndex, setActiveIndex] = useState(null);
const handleClick = (index) => {
if (index === activeIndex) {
setActiveIndex(null);
} else {
setActiveIndex(index);
}
};
return (
<div className="accordion">
{items.map((item, index) => (
<div
key={`accordion-index-${index}`}
className="max-w-md mx-auto transition-all ease-in-out duration-500 border-b-2"
>
<div
className="header bg-[#f5f5f5] text-[#444] cursor-pointer p-4 text-left text-lg flex justify-start items-center"
onClick={() => handleClick(index)}
>
<spna className="text-2xl text-blue-700">+</spna>
<h3 className="font-extrabold text-lg ml-7">{item.title}</h3>
</div>
{activeIndex === index && (
<div className="content px-0 py-5 overflow-hidden bg-[#fff] ">
<p className="text-left text-md">{item.content}</p>
</div>
)}
</div>
))}
</div>
);
}
export default Accordion;
import Accordion from "./Accordion";
function App() {
const items = [
{
title: "The first item of accordion",
content:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus suscipit tortor eget felis porttitor volutpat. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Curabitur aliquet quam id dui posuere blandit.",
},
{
title: "The second item of accordion",
content:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus suscipit tortor eget felis porttitor volutpat. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Curabitur aliquet quam id dui posuere blandit.",
},
{
title: "The third item of accordion",
content:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus suscipit tortor eget felis porttitor volutpat. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Curabitur aliquet quam id dui posuere blandit.",
},
];
return <Accordion items={items} />;
}
export default App;
That's it! You should now have a working accordion component in your ReactJS app.