HKS
HKS

Reputation: 1003

Styling the active link using the NavLink component from React Router is not working as expected

I have styled the active link in my React application using the NavLink component.

The problem I am facing is as follows:

enter image description here

When I click on the Contact Link, the active link styling is also getting applied to the Home link. I want only the Contact link to get the border-bottom styling.

What am I doing wrong?

The code snippets are as follows:

src/components/Header.js

import React from "react";
import { NavLink } from "react-router-dom";

const Header = () => {
  return (
    <nav>
      <ul>
        <li>
          <NavLink to="/" activeClassName="selected">
            Home
          </NavLink>
        </li>
        <li>
          <NavLink to="/about" activeClassName="selected">
            About
          </NavLink>
        </li>
        <li>
          <NavLink to="/contact" activeClassName="selected">
            Contact
          </NavLink>
        </li>
      </ul>
    </nav>
  );
};

export default Header;

src/App.js

import React from "react";
import About from "./components/About";
import Contact from "./components/Contact";
import Home from "./components/Home";
import Header from "./components/Header";
import { Switch, Route } from "react-router-dom";

const App = () => {
  return (
    <>
      <Header />
      <main>
        <Switch>
          <Route path="/about" exact>
            <About />
          </Route>
          <Route path="/contact" exact>
            <Contact />
          </Route>
          <Route path="/" exact>
            <Home />
          </Route>
        </Switch>
      </main>
    </>
  );
};

export default App;

Upvotes: 1

Views: 2615

Answers (2)

Chilaxathor
Chilaxathor

Reputation: 766

React Router v6:

Source: Active NavLink Classes with React Router

Now you can use the className property which now accepts a function and passes an isActive boolean property, like this:

<NavLink
  to="users"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Users
</NavLink>

You can also add multiple classes too, since v6 is out:

<NavLink
  to="users"
  className={({ isActive }) =>
    isActive ? 'bg-green-500 font-bold' : 'bg-red-500 font-thin'
  }
>
  Users
</NavLink>

Demo: Active NavLink Classes with React Router

Upvotes: 1

Long Nguyen Duc
Long Nguyen Duc

Reputation: 1325

Base on the react-router document, I think you should add exact prop on your NavLink to fix it.

https://reactrouter.com/web/api/NavLink

Upvotes: 0

Related Questions