Navigation Components in React

Photo by marianne bos on Unsplash

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.

--

--

--

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chindalath Traymany

Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

More from Medium

React Refactoring

Component Life Cycle in React Native

How to style React

React Components and Props