Hello everyone!
I'm currently working on a NextJS project and facing an issue with my dynamic accordion component. I'm using typescript, and the problem lies in only one accordion being able to open at a time. How can I ensure that only the specific one clicked on is toggled?
Currently, if there is already an active accordion, it automatically closes the previous one when attempting to open a new one. I want users to be able to open as many accordions as they wish without forcing the others to close.
Below is the snippet of my code:
import React, { useState } from 'react'
import { FaChevronDown, FaChevronUp } from 'react-icons/fa';
const faqList = () => {
const faqArr = [
// FAQs data
];
const [accordion, setActiveAccordion] = useState(-1);
let toggleAccordion = (id: number) => {
if (id === accordion) {
setActiveAccordion(-1);
return;
}
setActiveAccordion(id);
}
return (
<>
<div className='grid grid-cols-1 xl:grid-cols-2'>
{
faqArr.map((FAQ, id) =>
<div key={id} onClick={() => toggleAccordion(id)} className='accordionWrapper'>
<div className={accordion === id ? 'open' : ''}>
<div className='accordionHead'>
<h6>{FAQ.faqQuestion}</h6>
{ accordion === id ? (
<FaChevronUp />
) : (
<FaChevronDown />
) }
</div>
</div>
<div className={accordion === id ? 'content open' : 'content'}>
<p>{FAQ.answer}</p>
</div>
</div>)
}
</div>
</>
)
}
export default faqList