I am building this simple accordion and trying to grab the state (isActive) from the App component, the problem here is all contents open and close together when I try to open each one separately. these are two different components
Although the problem can be fixed if I create the state in the Accordion component, but I need to find a way to fix the problem when the state is passed from App component because I will need to use that state in App component for other things
can anyone help with example please
thanks
import React, { useState } from "react";
import Accordion from "./Accordion";
const App = () => {
const [isActive, setIsActive] = useState(false)
const accordionData = [
{
title: "Section 1",
content: `Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quis`
},
{
title: "Section 2",
content: `Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quis`
},
{
title: "Section 3",
content: `Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quis`
}
];
return (
<div>
<h1>React Accordion Demo</h1>
<div className="accordion">
{accordionData.map(({ title, content }) => (
<Accordion
setIsActive={setIsActive}
isActive={isActive}
title={title}
content={content}
/>
))}
</div>
</div>
);
};
export default App;
This is the Accordion component
import React from "react";
const Accordion = ({ title, content, isActive, setIsActive }) => {
return (
<div className="accordion-item">
<div className="accordion-title" onClick={() => setIsActive(!isActive)}>
<div>{title}</div>
<div>{isActive ? "-" : "+"}</div>
</div>
{isActive && <div className="accordion-content">{content}</div>}
</div>
);
};
export default Accordion;
This is what happens when I click on one of the + buttons it opens all contents
click on image