React show toggle showing all children

You can handle the the showDetails in the menu array itself as a property like below, when the menu is loaded it will have the default value which is false and after that the buttons would toggle it to true and false

const Menu = () => {
  const [menu, setMenu] = useState([
    {
      MenuText: "Submenu",
      SubMenus: [
        {
          MenuLink: "#",
          MenuText: "Submenu"
        }
      ]
    },

    {
      MenuText: "Submenu1",
      SubMenus: [
        {
          MenuLink: "#",
          MenuText: "Submenu"
        }
      ]
    }
  ]);

  return (
    <ul>
      {menu.map((row, i) => {
        return (
          <li className="footer-menu-icon footer-menu-item">
            <i
              className={`fas showSubLinks ${
                row.SubMenus.length >= 1
                  ? row.showDetails
                    ? "fa-minus"
                    : "fa-plus"
                  : "fa-angle-right"
              }`}
              onClick={() => {
                const updatedMenu = [...menu];
                updatedMenu[i].showDetails = !updatedMenu[i].showDetails;
                setMenu(updatedMenu);
              }}
            ></i>
            <a
              href={row.MenuLink}
              target={row.LinkTarget ? row.LinkTarget : "_self"}
            >
              {row.MenuText}
            </a>
            {row.SubMenus.length >= 1 && row.showDetails ? (
              <ul className="subMenu-items">
                {row.SubMenus.map((row) => {
                  return (
                    <li>
                      <a
                        href={row.MenuLink}
                        target={row.LinkTarget ? row.LinkTarget : "_self"}
                      >
                        {row.MenuText}
                      </a>
                    </li>
                  );
                })}
              </ul>
            ) : (
              <></>
            )}
          </li>
        );
      })}
    </ul>
  );
};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top