Hello! Welcome to the third lesson in our module on client-side routing with React Router.
In our previous lesson, we learned how to define our application's routes using the declarative JSX components <Routes> and <Route>. We now have a solid structure that maps different URL paths to specific page components. However, users can't yet move between these pages without manually typing in the URL.
Today, we'll bridge that gap. This lesson directly addresses the learning outcome: Implement navigation between routes using the <Link> and <NavLink> components. We will build the interactive navigation elements that allow users to seamlessly move through our single-page application.
Why Not Just Use an <a> Tag?
In a traditional multi-page website, you use the HTML <a> tag with an href attribute to link between pages. Clicking such a link triggers a full request to the server, which sends back a new HTML document. The entire page reloads, and any client-side state (like data in your React components) is lost.
In a Single-Page Application (SPA) built with React, this behavior is undesirable. We want to create the illusion of multiple pages while remaining within the single HTML document loaded initially. This is where React Router's navigation components come in.
The <Link> Component: Basic Navigation
The primary component for navigation in React Router is <Link>. It serves the same purpose as an <a> tag—creating a clickable link—but with a crucial difference: it prevents the full page reload.
When a user clicks a <Link>, React Router intercepts the event. Instead of letting the browser make a new request, it:
- Updates the URL in the browser's address bar using the HTML5 History API.
- Triggers a re-render of your React component tree.
- The
<Routes>component detects the URL change and renders the appropriate matching<Route>'s element.
This process is incredibly fast and preserves your application's state.
Learn React Router v6 In 45 Minutes
To see this in action, watch this short clip from the 'Learn React Router v6 In 45 Minutes' video by Web Dev Simplified. It clearly demonstrates the difference and the basic usage of the <Link> component.
Watch from 04:08 to 05:59. Notice how the to prop is used instead of href, and observe that only the content within the <Routes> block changes, not the entire page.
Let's add a simple navigation bar to our App.tsx from the last lesson.
// src/App.tsx
import { Routes, Route, Link } from 'react-router-dom';
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
import { NotFoundPage } from './pages/NotFoundPage';
function App() {
return (
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<hr />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
);
}
export default App;
Now, you have a basic navigation menu. Clicking "Home" or "About" will change the URL and render the correct component without a page refresh. Under the hood, React Router renders these as <a> tags, ensuring accessibility and standard browser features like "open in new tab" still work.
Advanced <Link> Props
The <Link> component has a few other useful props:
replace: If you setreplace={true}, clicking the link will replace the current entry in the browser's history stack instead of adding a new one. This is useful in scenarios like after a form submission (e.g., login), where you don't want the user to be able to click "back" and return to the form page.reloadDocument: If you do want to force a full page reload, you can usereloadDocument={true}. This bypasses client-side routing for that specific link.state: This allows you to pass along data with the navigation event, which is accessible in the destination component. This is a more advanced feature we'll touch on later.
The <NavLink> Component: Styling Active Links
For most navigation bars, you want to visually indicate which page the user is currently on. This is where <NavLink> is invaluable.
NavLink is a special version of <Link> that knows whether or not its to path matches the current URL. It provides hooks that allow you to apply styles or change content when the link is "active".
The official React Router documentation provides a very clear and concise explanation of NavLink and its capabilities.
Read the section on NavLink. Pay attention to the three ways you can leverage the active state: a default .active class, a function for the className prop, and a function for the style prop.
Let's refactor our navigation to use NavLink and add some styling for the active link. The most flexible method is to pass a function to the className or style prop. This function receives an object with an isActive boolean property.

Let's implement this. We'll use the style prop to make the active link bold.
// src/App.tsx (updated nav section)
import { Routes, Route, NavLink } from 'react-router-dom';
// ... other imports
// ... inside App component
<nav>
<ul>
<li>
<NavLink
to="/"
style={({ isActive }) => ({
fontWeight: isActive ? 'bold' : 'normal',
})}
>
Home
</NavLink>
</li>
<li>
<NavLink
to="/about"
style={({ isActive }) => ({
color: isActive ? 'red' : 'black',
})}
>
About
</NavLink>
</li>
</ul>
</nav>
// ...
With this change, the "Home" link will be bold when you are at the root URL (/), and the "About" link's text will turn red when you are on the /about page.
Building a Reusable Navigation Component
In a real application, you'd encapsulate your navigation logic in its own component. Let's create a Navbar component that generates links from an array of route definitions—a very common and maintainable pattern.
A Modular Approach to Integrating React-Router v6
This article from dev.to shows a great practical example of building a dynamic navigation bar by mapping over a routes array.
Read the sections 'Dynamic Navigation with NavLink' and 'Using NavLink in Header'. This demonstrates how to create a reusable header component that programmatically generates NavLink components from a list of routes.
Let's build our own version.
First, define the type for our route objects and the array itself. We can place this in a file like src/routes.ts.
// src/routes.ts
export interface AppRoute {
path: string;
label: string;
}
export const appRoutes: AppRoute[] = [
{ path: '/', label: 'Home' },
{ path: '/products', label: 'Products' },
{ path: '/about', label: 'About Us' },
];
Next, create the Navbar component.
// src/components/Navbar.tsx
import { NavLink } from 'react-router-dom';
import { AppRoute } from '../routes'; // Import our type definition
interface NavbarProps {
routes: AppRoute[];
}
export function Navbar({ routes }: NavbarProps) {
return (
<nav>
<ul>
{routes.map((route) => (
<li key={route.path}>
<NavLink
to={route.path}
className={({ isActive }) => isActive ? 'active-link' : 'inactive-link'}
>
{route.label}
</NavLink>
</li>
))}
</ul>
</nav>
);
}
// You can add some basic CSS in your index.css
/*
.active-link {
color: #007bff;
text-decoration: none;
font-weight: bold;
}
.inactive-link {
color: #333;
text-decoration: none;
}
*/
Finally, use it in App.tsx and add a new route for /products to see it all working.
// src/App.tsx
import { Routes, Route } from 'react-router-dom';
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
import { ProductListPage } from './pages/ProductListPage'; // Create this page
import { NotFoundPage } from './pages/NotFoundPage';
import { Navbar } from './components/Navbar';
import { appRoutes } from './routes';
function App() {
return (
<div>
<Navbar routes={appRoutes} />
<hr />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/products" element={<ProductListPage />} /> {/* New route */}
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
);
}
Fine-Tuning with the end Prop
There's one final detail to master with NavLink. Consider a scenario with nested routes, like /products and /products/1. If you have a NavLink with to="/products", it will be considered active for both URLs, because /products/1 starts with /products.
Often, this is not what you want. You want the /products link to be active only when the URL is exactly /products. To achieve this, you use the end prop.
Learn React Router v6 In 45 Minutes
This final clip from the Web Dev Simplified video provides an excellent explanation of why and how to use the end prop.
Watch from 03:52 to 04:20. The video uses a books example, which is analogous to our products example. Note how adding the end prop changes the active state behavior for the parent route link.
In our Navbar component, we should add the end prop to our root link to prevent it from being active on every page.
// src/components/Navbar.tsx (updated)
// ...
<NavLink
to={route.path}
// If the path is '/', use the end prop. For others, it's often desired
// to have the parent active (e.g. /products active on /products/1), so
// we can omit `end` for those. This is a design choice.
end={route.path === '/'}
className={({ isActive }) => isActive ? 'active-link' : 'inactive-link'}
>
{route.label}
</NavLink>
// ...
Test your understanding!
You are building a settings page for a user dashboard. You have the following routes:
/settings/profile/settings/account/settings/notifications
Create a SettingsNav component that displays these three links using <NavLink>. The active link should have a background color of lightgray. The links should not use the end prop, allowing a parent /settings link (if one existed) to remain active.
Show answer
// src/components/SettingsNav.tsx
import { NavLink } from 'react-router-dom';
export function SettingsNav() {
const links = [
{ path: '/settings/profile', label: 'Profile' },
{ path: '/settings/account', label: 'Account' },
{ path: '/settings/notifications', label: 'Notifications' },
];
return (
<nav>
{links.map(link => (
<NavLink
key={link.path}
to={link.path}
style={({ isActive }) => ({
display: 'block',
padding: '8px',
backgroundColor: isActive ? 'lightgray' : 'transparent',
})}
>
{link.label}
</NavLink>
))}
</nav>
);
}
// In your main layout for the settings section, you would render <SettingsNav />
// alongside an <Outlet /> for the child routes, a concept we will cover soon.
Conclusion
You've now mastered the art of declarative navigation in React Router! By replacing traditional <a> tags with <Link> and <NavLink>, you can build a fast, fluid, and professional user experience that is the hallmark of a well-crafted SPA.
Key Takeaways:
- Use the
<Link>component for basic client-side navigation that avoids full page reloads. It uses thetoprop to specify the destination. - Use the
<NavLink>component when you need to style a link based on whether it is "active". <NavLink>provides anisActiveboolean via itsstyle,className, andchildrenfunction props, giving you full control over active state styling.- The
endprop on<NavLink>ensures that the link is only considered active when the URL path matches exactly, which is crucial for parent routes. - Encapsulating navigation in a dedicated, reusable component that maps over a routes array is a robust and scalable pattern.
Preview of the Next Lesson:
We've now created links to static pages like /about and dynamic-looking pages like /products. But what about a specific product, like /products/123? In our next lesson, we will learn how to access dynamic URL parameters using the useParams hook, which will allow our components to read values like 123 directly from the URL and fetch the correct data.