Navigation Components in React
React gives us Link
and NavLink
components, which both allow us to navigate through different routes. But what differentiates them from the anchor tag, and when should we use what?
Anchor
The traditional<a>
tag also allows to navigate through webpages, but refreshes the page each time. We specify the destination with the href
attribute.
Link
The Link
component does not refresh the entire page — only specific components get re-rendered when it navigates to an existing route defined by the Route
component.
Below is an example of both anchor
and Link
.
import { Link } from 'react-router-dom';function MobileNavbar() { return ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> <a href="https://www.linkedin.com/">LinkedIn</a> </nav> <Route path="/about" exact>{AboutComponent}</Route> <Route path="/">{HomeComponent}</Route> )}export default MobileNavbar
NavLink
The NavLink
component is similar to the Link
component, except it gives us more styling options through props. One prop is the activeClassName
, which is shown below.
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about" activeClassName="active">About</NavLink>
</nav>
When we specify the activeClassName
prop, NavLink
adds the class name to the element when it is clicked on, or active.