I'm working on react js and I make a dashboard with sidebar(sidenav) in my sidebar I have a menu with submenu's And I want the collapse menus automatically when I click on one of the menus to be opened
<div className="main-menu">
<ul>
{MenuItems.map((menuItem, key) => (
<MenuItem
key={key}
name={menuItem.name}
iconName={menuItem.iconName}
subMenu={menuItem.subMenu || []}
/>
))}
</ul>
</div>
import React, { useState } from "react";
import { Link } from "react-router-dom";
const MenuItem = (props) => {
const { name, subMenu, iconName } = props;
const [expand, setExpand] = useState(false);
return (
<li onClick={props.onClick}>
<a
href="#"
onClick={() => {
setExpand(!expand);
}}
className={`menu-item ${expand ? "active" : ""}`}
>
<div className="menu-icon">
<span>{iconName}</span>
</div>
<span>{name}</span>
</a>
{subMenu && subMenu.length > -0 ? (
<ul className={`sub-menu ${expand ? "active" : ""}`}>
{subMenu.map((menu, index, to) => (
<li key={index} className={`${expand ? "active" : ""}`}>
<Link to={menu.to}>{menu.name}</Link>
</li>
))}
</ul>
) : null}
</li>
);
};
export default MenuItem;
If the subMenu prop has an id or a unique value, you can add another variable which will be the opend subMenu id
something like:
const [opendMenuId, setOpendMenuId] = useState(null); // no menu is open by default
and for the className
{subMenu.map((menu, index, to) => (
<li key={index} className={`${opendMenuId === menu.id ? "active" : ""}`}>
<Link to={menu.to}>{menu.name}</Link>
</li>
)}