'bootstrap React Collapse Multi

I am new to react. I have a sidebar with collapsible links (nested). It will be a huge chunk of code if i write function for each of them and will also get complicated. Is there a way using 'this' to manage all with 1 function? (not using accordion)

function Example() {
  const [open, setOpen] = useState(false);

  return (
<>
  <Button
    onClick={() => setOpen(!open)}
    aria-controls="example-collapse-text"
    aria-expanded={open}
  >
    click
  </Button>
  <Collapse in={open}>
    <div id="example-collapse-text">
      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus
      terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer
      labore wes anderson cred nesciunt sapiente ea proident.
    </div>
  </Collapse>
</>
  );
}

render(<Example />);


Solution 1:[1]

The basic idea here is to have an object as state with property name same as link name/id and property value as boolean:

{
    1: false,
    2: false,
    3: false
}

You can then write a callback function which has link name/id as parameter and which is called onClick:

const handleClick = (navId) =>
    setNavState((prev) => {
      return { ...prev, [navId]: !prev[navId] };
    });

In your link then:

onClick={() => handleClick(nav.id)}

I have also set up a sandbox with working example: https://codesandbox.io/s/react-bootstrap-template-forked-2mhh3j

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Igor Gonak