Using React Router  to Specify Which Element in a Navigation Bar Is Active

Using React Router to Specify Which Element in a Navigation Bar Is Active

The React Router DOM package gives us <NavLink> and <Link> components. This blog post will cover the difference between the two components and how <NavLink> can be used to specify the link that is active in an application?s navigation bar.

Image for post

Both <NavLink> and <Link> components can be used to define and design a declarative navigation around an application. Within either component, we can use the ?to? attribute to specify the location pathname to which the link will direct. After installing react-router-dom and importing <Link> into a file, the component implementation would look something like this:

import { Link } from ‘react-router-dom'<Link to=”/about”>About</Link>

You can implement <NavLink> in the same way:

import { NavLink } from ‘react-router-dom'<NavLink to=”/about”>About</NavLink>

Both compiles into html code that looks like this:

Image for post

The main functionality of these components seems to be the same. So why the need for both? It turns out <NavLink> comes with additional styling attributes that allow us to stylize and differentiate the link that is ?active?.

Take this for example:

This NavBar React component enables navigation to four routes ? ?/?, ?/search?, ?/map?, and ?/login? ? using the good old <Link> component.

Image for post

As shown above, we can successfully navigate to the pathnames that each <Link> component is associated with.

Here?s what sets the two components apart. <NavLink> gives us an additional ?activeClassName? attribute. We can point this attribute to a CSS class name and specify how the active link will be differentiated.

The following CSS selectors are written to render a solid line both when we hover over an anchor tag and when a specific anchor tag is chosen.

Image for post

With <NavLink>, we are able to add styling attributes to the ?active? element to visually differentiate the link whose pathname matches the current URL.

Hope this helps you in implementing a more interactive navigation bar!

The official documentation for these components can be found here:

  • <NavLink>
  • <Link>
17