Answer the question
In order to leave comments, you need to log in
How to make only one accordion element open at a time?
There is an accordion . You need to make sure that when you click on the button, the previously opened element is closed, i.e. There was only one open at a time. How to implement this?
Answer the question
In order to leave comments, you need to log in
const AccordionItem = ({ title, opened, toggle, children }) => (
<div>
<button onClick={toggle}>{title}</button>
{opened && children}
</div>
);
const Accordion = ({ items }) => {
const [ opened, setOpened ] = useState(null);
return (
<div>
{items.map((n, i) => (
<AccordionItem
title={n.title}
opened={i === opened}
toggle={setOpened.bind(null, i === opened ? null : i)}
>
<p>{n.text}</p>
</AccordionItem>
))}
</div>
);
};
Well, if each element of the accardion has its own unique id, then store the id of the open element in the state. Do something like this for each element
const [openId, setOpenId] = useState();
return (<>{elems.map(el => <AccElement key={el.id} open={opendId===el.id} onClick={() => setOpenId(el.id)} data={el} />}</>);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question