I want the accordion clicked to open up, like show the description it has. But here when I click on one of them, all of them open at the same time. I'm fetching data from a local js File and the data is simply list of objects containing two things - ques and ans
const [ show,setShow ] = useState(false)
return (
<div className="Faq">
{
Faq_Data.map((value, index) => {
return(<div className="Faq_Item" key={index}>
<div className="Faq_Item_Plate" onClick={()=>setShow(!show)} >
<div className="Faq_Item_Button">
{value.ques}
</div>
<img src="/img/critical/plus.png" alt="" />
</div>
{
show && <div className="Faq_Item_Desc">{value.ans}</div>
}
</div>)
})
}
</div>
All your accordions are opening because they all use the same show value. You'll need individual values for all the different accordions to achieve what you want.
One solution would be to store an array of booleans:
// Initialise the state with an array of `false` values,
// each value corresponding to an element of the data array
const [shown, setShown] = useState(Array.from(faqData).fill(false));
return faqData.map(
// Only do this if you don't have a unique id you could use instead of the index
// See https://reactjs.org/docs/lists-and-keys.html#keys
(faqItem, index) => <div key={index}>
<button onClick={() => setShown(
arr => arr.map(
(tmpShow, tmpIdx) =>
index === tmpIdx
? !tmpShow
: tmpShow
)
)}>
{faqItem.question}
</button>
{shown[i] && <div>{faqItem.answer}</div>}
</div>
);
But the better, more idiomatic solution would be to have separate accordion components that accept the question details as props and handle their own "open/closed" state. You should also consider using the <details> element instead of <div>s — both because it's semantically correct here and because it handles the behaviour you seem to be after without any additional coding from you.