Home > Net >  Toggle active class for only currently selected link in React hooks
Toggle active class for only currently selected link in React hooks

Time:08-09

I'm drawing a blank on how to toggle an active class on links for a header. I currently have the class applied, but it toggles the class for all links with the function. I need to be able to toggle the current class only the selected link:

const [isActive, setActive] = useState(false);
const toggleClass = () => {
    setActive(!isActive);
};
<li>
  <a className={isActive ? "current" : null} href="#home" onClick={toggleClass}>
    Home
  </a>
</li>
<li>
  <a className={isActive ? "current" : null} href="#about" onClick={toggleClass}>
    About
  </a>
</li>
<li>
  <a className={isActive ? "current" : null} href="#contact" onClick={toggleClass}>
    Contact
  </a>
</li>

CodePudding user response:

You are using the same state for all your links. This wouldn't work, in less you change it a little bit. You can for example set isActive to the clicked link hash. Like so:

const [isActive, setActive] = useState("");
const toggleClass = (e) => {
  setActive(e.currentTarget.hash);
};
<li>
  <a className={isActive == "#home" ? "current" : ""} href="#home" onClick={toggleClass}>
    Home
  </a>
</li>
<li>
  <a className={isActive == "#about" ? "current" : ""} href="#about" onClick={toggleClass}>
    About
  </a>
</li>
<li>
  <a
    className={isActive == "#contact" ? "current" : ""}
    href="#contact"
    onClick={toggleClass}
  >
    Contact
  </a>
</li>
  • Related