How to Make Links Active with React Router v5?

Sometimes, we want to make links active with React Router v5.

In this article, we’ll look at how to make links active with React Router v5.

Make Links Active with React Router v5

To make links active with React Router v5, we can use the NavLink component to add our links.

Then we add the activeClassName to set the class name for active links.

For instance, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink
} from "react-router-dom";

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  return <p>bar</p>;
};

export default function App() {
  return (
    <Router>
      <style>{`.is-active { font-weight: bold }`}</style>
      <div>
        <ul>
          <li>
            <NavLink to="/foo" activeClassName="is-active">
              foo
            </NavLink>
          </li>
          <li>
            <NavLink to="/bar" activeClassName="is-active">
              bar
            </NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

We add the Routes to map the URLs to the components to render.

Then we add the NavLinks to add links that lets us set the class name of the active link.

We set activeClassName to a string for the class name of the active link.

In the style element, we add a string to style anything with the is-active class by making the font bold.

Therefore, when we click on the links, we’ll see the link for the current page bolded.

Conclusion

To make links active with React Router v5, we can use the NavLink component to add our links.

Then we add the activeClassName to set the class name for active links.