Link and NavLink
- React course
- Intermediate
- Lesson 39/80
- 4 min
Learn to change pages with Link and track active state with NavLink.
Link and NavLink
<Link to="..."> is React Router's basic navigation component. On click, it changes the URL; no page reload.
<NavLink to="..."> is a special variant of Link. When on the active route, it adds the active class to className. This is ideal for highlighting the active item in a menu.
Both take the to prop. Link for plain navigation, NavLink for active highlighting. NavLink is preferred in menus where you want styling.
Menu example
For a navigation menu, NavLink is ideal. <nav><NavLink to="/">Home</NavLink><NavLink to="/about">About</NavLink></nav>.
On the active route, NavLink automatically gets class="active". With CSS .active { '{ font-weight: bold; }' }, the active item appears bold.
This pattern is one of the cleanest ways to show users which page they're on. You get an accessible menu without code clutter.
Practice Write menu
Complete the skeleton. Write a NavBar component. Inside <nav>, have two NavLinks: <NavLink to="/">Home</NavLink> and <NavLink to="/about">About</NavLink>. Export it. (Assume NavLink is imported.)
Starter code
// Write the NavBar component hereSample solution
function NavBar() {
return (
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
</nav>
);
}
export default NavBar;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which adds a class on the active route?
- Route
- Link
- BrowserRouter
- NavLink Correct answer
Explanation: NavLink adds a class on active route.
2 Link prop
Link and NavLink's common prop is ____.
Link and NavLink's common prop is to.
Explanation: Common prop is 'to'.
3 Match Link and NavLink
| Term | Meaning |
|---|---|
Link |
plain |
NavLink |
active highlight |
to |
prop |
.active |
CSS |