In React, you can create links to your frontend routes using the Link and NavLink components provided by react-router-dom. These components enable navigation without full-page reloads, maintaining a smooth user experience.
By the end of this reading, you should be able to:
The Link component creates a navigable link in a React application.
import { Link } from 'react-router-dom';
function Example() {
return (
Create a Team!
);
}
A Link ultimately resolves to an <a href> tag but prevents a full-page reload. Instead, it updates the browser’s history and location, ensuring a seamless navigation experience.
The to prop determines the target route:
function Teams() {
return Create a Team!; // Takes user to `/teams/new`
}
function Teams() {
return Create a Team!; // Takes user to `/teams/new`
}
Relative paths extend the parent component’s route, making nested routing more flexible. Absolute paths always start from the root of the application.
The NavLink component behaves like a Link but includes automatic styling for active and pending states.
import { NavLink } from 'react-router-dom';
function Navigation() {
return (
);
}
By default, a NavLink adds an active class to the link when its to prop matches the current URL.
A NavLink remains active as long as its to prop matches the beginning of the current URL. This means /teams will also be active at /teams/1. To prevent this, use the end prop:
Now, the Teams link will only be active at /teams, but not at /teams/1.
Links and NavLinks will only work if they are inside a router. Attempting to use them outside of a RouterProvider or its enclosed components will produce an error.
In this reading, you learned how to:
Link to create frontend navigationNavLink to highlight active routesTo deepen your understanding, explore these topics:
The Link and NavLink components enable smooth navigation in React applications. By mastering them, you can create seamless, dynamic, and user-friendly web experiences.