Search code examples
javascriptreactjssemantic-ui

How could I make the accordion close?


Need some brainstorming ideas, basically as you can see in the code when I click the title of the accordion the index gets passed of the title. The accordion closes due to the 'active' property in the class name. Now I want to implement a feature so that if you click an already opened accordion it will close. I tried multiple things but I have come to no solution.

Thanks in advance

const Accordion = ({ accordionInfo }) => {
  const [open, setOpen] = useState(null);

  const onTitleClick = (index) => {
    setOpen(index);
  };

  const accordion = accordionInfo.map((info, index) => {
    const active = open === index ? 'active' : false;
    return (
      <div key={info.title}>
        <div className='ui styled accordion'>
          <div
            className={`${active} title`}
            onClick={() => onTitleClick(index)}>
            <i className='dropdown icon'></i>
            {info.title}
          </div>
          <div className={`${active} content`}>
            <p>{info.description}</p>
          </div>
        </div>
      </div>
    );
  });
  return <div>{accordion}</div>;
};

Solution

  • I believe that setting open as null if index is same as open should do what you need

    Something like:

    const onTitleClick = (index) => {
        setOpen(index === open ? null : index);
    };