Maintain usestate for different onclick

Viewed 39

Since I am new to react i am trying to maintain state separately for each onclick


  const openMenu = (id) => {
    setNavbarOpen(!navbarOpen);
     closeMenu();
  };

const closeMenu = () => {
    setMenuActive(false);

  };
<navContainer isMenuActive={isMenuActive}>
<ul>
                {navItems.map((navItem) => (
                  <NavItem
                    data={navItem}
                    key={navItem.id}

                    onClick={() => openMenu(navItem)}
                  />
                ))}
              </ul>
</navContainer>

I am planning to open the menu and close the menu while clicking on same tab. If first menu is open then first menu should close while clicking. If I click the second menu instead of closing the first menu the second menu should opened. Now if i click the second menu the first menu gets closed and the second menu is not opening.

Basically I would like to maintain the state separately for each menu. Is it possible or any other ideas?

1 Answers

In your .map() function, you can pass in the name or id of your tab then add that to your state.

Then you can create your logic based on the value of tab which will either be equal to the name of the corresponding opened tab or null if the tab is closed.

const tabs = [
  {
    id: 0,
    name: "tab1"
  },
  {
    id: 1,
    name: "tab2"
  },
]

export default function App() {
  const [tab, setTab] = useState(null)

  const handleOpenTab = (e) => {
    tab === e.target.value 
      ? setTab(null)
      : setTab(e.target.value)
  }

  return (
    <div className="App">
      {tabs.map(tab => (
        <input
          key={tab.id}
          onClick={e => handleOpenTab(e)}
          type="button"
          value={tab.name}
        />
      ))}
      <pre>
        {
          JSON.stringify(tab, null, 2)
        }
      </pre>
    </div>
  );
}

Edit Add to state from map

Related