Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a class on click, and remove the same class from all other elements?

I have a button navigation and when you click on a button, the active class is added. My goal is for the active class to be added to the button clicked, but remove that class of active on all other buttons if present. The ‘About’ button will have a class of active on page load.

Not sure how to translate this to React, in JavaScript on click I would remove the class from all the elements in a loop and add a class to the target clicked if it did not already have the active class.

Code Sandbox – https://codesandbox.io/s/toggle-active-on-class-clicked-remove-from-the-rest-r467l1?file=/src/App.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function Header() {
  const [active, setActive] = useState(true);

  const toggleColor = function (e) {
    // on load, 'About' button has active class
    // when clicking another menu item add active class, remove active from the rest of buttons
    console.log(e.target);
  };

  return (
    <header className="header-img-container">
      <nav>
        <ul>
          <li>
            <button onClick={toggleColor} className={active ? "active" : ""}>
              About
            </button>
          </li>
          <li>
            <button onClick={toggleColor}>Skills</button>
          </li>
          <li>
            <button onClick={toggleColor}>Projects</button>
          </li>
          <li>
            <button onClick={toggleColor}>Words</button>
          </li>
        </ul>
      </nav>
    </header>
  );
}

>Solution :

There are so many ways to solve that problem. You can try this if it’s meet your requirements.

import "./styles.css";

import { useState } from "react";

const list = ["About", "Skills", "Projects", "Words"];

export default function Header() {
  const [activeLink, setActiveLink] = useState("About");

  return (
    <header className="header-img-container">
      <nav>
        <ul>
          {list.map((item) => (
            <li key={item}>
              <button
                onClick={() => setActiveLink(item)}
                className={activeLink === item ? "active" : ""}
              >
                {item}
              </button>
            </li>
          ))}
        </ul>
      </nav>
    </header>
  );
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading