Home > other >  All my sidebar menu opens at once in ReactJS
All my sidebar menu opens at once in ReactJS

Time:11-19

I am trying to create a sidebar menu with dropdwon

For I single menu it works fine but if I have multiple dropdown

All opens at one when I click on the menu to open the submenu.

I am getting the data for the menu from a json array

const SidebarItems = ({ items }) => {
    const [open, setOpen] = useState(false)

    return (
        <div>
            {items && items.map((item, index) => {
                return (
                    <div key={index}>
                        <div>
                            <li >
                                <div className="nav-items" onClick={() => setOpen(!open)}>
                                    <span>
                                        <i className="bi-badge-vr" />
                                        {item.title}
                                    </span>
                                    <i className="bi-chevron-down" />
                                </div>
                            </li>
                        </div>

                        <div className={open ? 'sub-menu sub-menu-open' : "sub-menu"} >
                            {item.chidren && item.chidren.map((sub_menu, sub_index) => {
                                return (
                                    <div key={sub_menu}>
                                        <Link to="manager/staff/create">
                                            <span>
                                                <i className="bi-badge-vr" />
                                                {sub_menu.title}
                                            </span>
                                        </Link>

                                    </div>
                                )
                            })}

                        </div>

                    </div>
                )
            })}
        </div>
    )
}

CodePudding user response:

This is because they all use the same state. Move the item to its own component so I can keep its own state:

const Item = ({ item }) => {
  const [open, setOpen] = useState(false);

  return <Your item code here />;
};

And in SideBarItems:

items.map((item, index) => {
  return <Item item={item} key={index} />;
});
  • Related