React active navlink not working - home link always in active state

Viewed 17

I am trying to add an active class to the nav link of the page you are on, however, no matter which page you are on, the homepage always has the active class. As you can see here, both home and about are green when on the about page - https://gyazo.com/8ad3f7c455075bad53344372d56b9b4a

My code is below. When I checked this in the console with logs, it seems the home navlink is always in an active state, why is this? https://gyazo.com/40faf1ee4a076d78edff7596daa44845

In past react apps, I just used the activeClassName and it worked fine

import React from "react";
import { NavLink } from "react-router-dom";
import "./../App.css";

function Navbar() {
  return (
    <nav>
      <NavLink
        to="/"
        className={({ isActive }) => "nav-link" + (isActive ? " active" : "")}
      >
        <span className="nav-text">Home</span>
      </NavLink>
      <NavLink
        to="/about"
        className={({ isActive }) => "nav-link" + (isActive ? " active" : "")}
      >
        <span className="nav-text">About</span>
      </NavLink>
      <NavLink
        to="/services"
        className={({ isActive }) => "nav-link" + (isActive ? " active" : "")}
      >
        <span className="nav-text">Services</span>
      </NavLink>
      <NavLink
        to="/contact"
        className={({ isActive }) => "nav-link" + (isActive ? " active" : "")}
      >
        <span className="nav-text">Contact</span>
      </NavLink>
    </nav>
  );
}

export default Navbar;

0 Answers
Related