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

Time:10-04

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;

CodePudding user response:

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

  • Related