Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
collapsing all other menu when one is expanded

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;

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!