E
E
Evgeii2021-10-16 23:19:21
React
Evgeii, 2021-10-16 23:19:21

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

2 answer(s)
0
0xD34F, 2021-10-16
@Evgeii

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>
  );
};

B
bitwheeze, 2021-10-16
@bitwheeze

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 question

Ask a Question

731 491 924 answers to any question