Home > OS >  React - toggleClass on button activate all buttons
React - toggleClass on button activate all buttons

Time:09-16

I'm trying to make navigation menu similiar to the nav menu in reactjs.org I'm using Header component and navigation which is objects with links and name. I'm adding class onClick using the state but this toggle all buttons.

import React, { useState } from "react";
import styles from "./index.module.css";
import getNavigation from "../../utils/navigation";
import { Link } from "react-router-dom";
import logo from "../../images/europa-logo.png";

const Header = () => {
  const links = getNavigation();
  const [isActive, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!isActive);
  };

  return (
<div>
  <nav className={styles.topnav}>
    <div className={styles.pageWrapper}>
      <img src={logo} alt="Logo" />

      <ul>
        {links.map((l, i) => (
          <li key={i}>
            <Link
              className={isActive ? "btn-active" : null}
              onClick={toggleClass}
              to={l.link}
              value={l.title}
            >
              {l.title}
            </Link>
          </li>
        ))}

        <li>
          {" "}
          <div className={styles.social}>
            <a href="https://facebook.com">
              <FontAwesomeIcon
                size="2x"
                icon={["fab", "facebook-square"]}
              />{" "}
            </a>

            <a href="mailto:[email protected]">
              <FontAwesomeIcon size="2x" icon="envelope" />
            </a>
          </div>
        </li>
      </ul>
    </div>
  </nav>
</div>
  );
};

export default Header;

The result is all buttons are activated: Nav-menu

My goal is to activate only the link which is clicked and the first button in nav menu need to be activated by default. What I'm doing wrong?

CodePudding user response:

You can use <NavLink> instead of simple <Link> is a special version of the that will add styling attributes to the rendered element when it matches the current URL.

<NavLink to="/" activeClassName="active">Link</NavLink>

You can check the docs here: https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/docs/api/NavLink.md

CodePudding user response:

You can define active index and your condition look like this

className={activeIndex === i ? "btn-active" : ""}

Toggle class function:

const [activeIndex, setActiveIndex] = useState(0);

  const toggleClass = (i) => {
    setActiveIndex(i);
  };

and onClick will look like this

onClick={()=>{toggleClass(i);}}
  • Related