React State Hook - toggle a class

I think you just need

const [ menuActive, setMenuState ] = useState(false);

change the name of setState to setMenuState in your code also


Just make the className dynamic, so instead of setting

<li className="p-sidebar-menu-item">

transform it in a template literal

<li className={`p-sidebar-menu-item`}>

and then add your class conditionally (the "yellow" class in my example)

<li className={`p-sidebar-menu-item ${menuActive ? "yellow" : ""}`}>

Take a look at this CodeSandbox: here I've just added your component and changed the way the className attribute is generated.

If you want to avoid the ternary operator you could use the classnames module and then update your code to

import c from "classnames";
...
...
...
<li className={c("p-sidebar-menu-item", {yellow: menuActive})}>

Another clean solution can be to generate the className string in advance, for example

let classes = "p-sidebar-menu-item";
if(menuActive) {
  classes += " yellow";
}
<li className={classes}>

Let me know if you need some more help 😉