What is NavLink in React Router
This article provides a comprehensive overview of the
NavLink component in React Router. You will learn what
NavLink is, how it differs from the standard
Link component, and how to implement it to create dynamic,
styled navigation menus in your React applications.
Understanding the NavLink Component
The NavLink component is a helper component provided by
the react-router-dom library. It is a subclass of the
standard Link component, designed specifically for building
navigation bars and menus.
The primary feature of NavLink is its ability to detect
whether the current URL matches the path specified in its
to prop. When a match is detected, the component
automatically applies an “active” state, allowing you to style the
active navigation link differently than the inactive ones.
NavLink vs. Link: The Key Difference
While both components are used to navigate between different routes without reloading the browser page, they serve different purposes:
Link: Used for general navigation anywhere on a page (e.g., linking to a blog post, a user profile, or a terms of service page). It does not track whether it is active.NavLink: Used specifically for navigation menus (e.g., header navs, sidebars). It tracks the active state, making it easy to highlight the current page the user is viewing.
How to Use NavLink in React Router v6
In React Router v6, NavLink utilizes a function-based
approach to apply dynamic styles or classes based on the active state.
The component passes an isActive boolean property to its
className and style props.
1. Dynamic Class Styling
You can dynamically apply CSS classes by passing a function to the
className prop:
import { NavLink } from 'react-router-dom';
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>
</nav>
);
}2. Dynamic Inline Styling
Similarly, you can apply inline styles dynamically using the
style prop:
<NavLink
to="/contact"
style={({ isActive }) => ({
color: isActive ? 'red' : 'black',
textDecoration: 'none'
})}
>
Contact
</NavLink>The “end” Prop
By default, a NavLink is considered active if its path
matches the beginning of the current URL. For example, a link to
/ (Home) would remain active even when the user navigates
to /about.
To prevent this behavior and ensure the link is only active when
there is an exact match, use the end prop:
<NavLink to="/" end>
Home
</NavLink>