How to Implement NavLink in React Router

This article provides a straightforward guide on how to implement the NavLink component in React using React Router. You will learn how to set up navigation, apply active styles to highlight the current route, and customize class names to improve the user experience of your application’s navigation bar.

The NavLink component is a wrapper around the standard Link component in react-router-dom. It is specifically designed for building navigation menus because it knows whether the current URL matches its to prop. This allows you to easily apply styling or CSS classes to the active link so users know which page they are currently viewing.

Step 1: Install React Router

Before using NavLink, ensure you have react-router-dom installed in your React project. You can install it using npm or yarn:

npm install react-router-dom

Import the NavLink component from react-router-dom at the top of your navigation component file:

import { NavLink } from 'react-router-dom';

In React Router v6, you can apply active styling dynamically by passing a function to the className or style props. This function receives an object with an isActive property, which is a boolean.

Here is a complete example of a navigation component using NavLink:

import React from 'react';
import { NavLink } from 'react-router-dom';
import './Navigation.css'; // Assume this file contains your styles

function Navigation() {
  return (
    <nav>
      <NavLink 
        to="/" 
        className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}
      >
        Home
      </NavLink>

      <NavLink 
        to="/about" 
        className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}
      >
        About
      </NavLink>

      <NavLink 
        to="/contact" 
        className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}
      >
        Contact
      </NavLink>
    </nav>
  );
}

export default Navigation;

Step 4: Add CSS for the Active Class

To make the active state visible to the user, define the .active class in your CSS file:

.nav-link {
  text-decoration: none;
  color: #333;
  margin: 0 10px;
  font-weight: normal;
}

.nav-link.active {
  color: #007bff;
  font-weight: bold;
  border-bottom: 2px solid #007bff;
}

If you prefer inline styles instead of CSS classes, you can use the same functional approach with the style prop:

<NavLink
  to="/about"
  style={({ isActive }) => ({
    color: isActive ? 'blue' : 'black',
    fontWeight: isActive ? 'bold' : 'normal',
  })}
>
  About
</NavLink>