Logo

dev-resources.site

for different kinds of informations.

Link Component in React Router

Published at
9/19/2023
Categories
react
reactrouter
link
component
Author
alexanie_
Categories
4 categories in total
react
open
reactrouter
open
link
open
component
open
Author
9 person written this
alexanie_
open
Link Component in React Router

Introduction

Natively, web pages are required to be linked (hyperlink) together for navigation. This navigation involves moving from one web page to another web page in the same domain (website) or a different domain on the web.

However, navigation on the web does not only involve moving from one web page to another but also moving from one section (hash) to another on the same web page.

Natively, navigating using the <a> tag requires the entire web page to reload. This might lead to slow navigation depending on the amount of content on the web page and other asynchronous request the browser has to do in other to fetch third-party resources like APIs.

The <Link> Component in React Router is built to handle routing (navigation) on the client side and prevent the web page from reloading for easy navigation.

In this blog post, I explained what the <Link> Component in React Router is, how to implement client side router using props from the <Link> Component. I also talked about HTML attributes that can be used with the <Link> Component.

By the end of this blog post, you should be able to implement the <Link> Component in your project and have a clear understanding of how the <Link> Component aid client-side router in React.

Perquisites

To follow along, you should have a basic understanding of the following.

  1. How to set up a React App

  2. How to install React Router

Link Component

A <Link> is a Component in React Router used for client-side routing. The <Link> Component is equivalent to the <a> tag in HTML, that is when the <Link> Component renders in the DOM, it returns the normal <a> tag.

The <Link> helps the user navigate from one component to another in an SPA (Single-page application) without reloading the entire web page.

To have a better understanding of how the <Link> Component works in React let's take a look at how the browser handles the <a> tag when a user clicks on it.

In the Navbar.js file, add the <a> tag as indicated below.

<ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="blogs">Blogs</a>
            </li>
            <li>
              <a href="contact">Contacts</a>
            </li>
 </ul>
Enter fullscreen mode Exit fullscreen mode

When any of the navlinks is clicked, it reloads the entire web page before displaying the next page.

See a Codesandbox below.

%[https://codesandbox.io/p/sandbox/dreamy-shtern-pnh2d8?file=%2Fsrc%2Fcomponents%2FBlogCard.js%3A48%2C1]

Click on any of the nav links to navigate to a different page. Notice how the browser reloads before loading the next page.

This page reload can be stopped using the <Link> component.

import { Link } from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

To begin using the <Link> Component, import it from the react-router-dom as indicated above.

Then change the <a> from the codebase to a <Link> tag.

<ul>
         <li>
              <Link to="/">Home</Link>
          </li>
          <li>
              <Link to="blogs">Blogs</Link>
          </li>
          <li>
              <Link to="contact">Contacts</Link>
          </li>
  </ul>
Enter fullscreen mode Exit fullscreen mode

Here is a Codesandbox example below.

%[https://codesandbox.io/s/02-link-compenet-jww7sm?from-embed]

Here, clicking the nav links navigates to the next page without reloading the web page.

The <Link> Component can do much more, than prevent the browser from reloading. You can determine how the <Link> Component responds to a user click using the defined props.

Props

Props in react are referred to as properties, the <Link> Component comes with some defined props that can be applied to the <Link> Component the same way HTML attribute is applied to HTML tags.

This is very useful when you want to apply a specific function on how the <Link> Component should behave when a user clicks on it.

The <Link> Component props include.

  • to

  • reloadDocument

  • replace

  • preventScrollReset

  • relative

  • state

Each prop functions differently and determines how the <Link> Component responds to user click.

to

The to props (property) is equivalent to the href attribute of the <a> tag. The to props is used to handle routing, by specifying the relative or absolute path the <Link> should navigate to when a user clicks on it.

// Link Component
<Link to="/">Home</Link>

// HTML equivalent
<a href="home"></a>
Enter fullscreen mode Exit fullscreen mode

In the Navbar.js file, the to props is used to specify a relative path that links different components together on the navbar. However, an absolute link can also be specified to direct the user to a different destination on the web.

See the Codesandbox below.

Click the blogs section and click on any of the cards.

%[https://codesandbox.io/s/02-link-compenet-jww7sm?file=/src/pages/Blogs.js]

Here, from the above code, the blogs section contains six cards with an absolute path to direct the user to a different domain on the web page.

reloadDocument

Just as the name implied, the reloadDocument props reload the entire web page when a user clicks on the <Link> Component. This is the native behavior of the <a> tag.

To specify the reloadDocument props apply it on the <Link> Component like so 👇

<Link to="/" reloadDocument> Home </Link>
Enter fullscreen mode Exit fullscreen mode

Click on the nav link to reload the document and navigate to the next page

%[https://codesandbox.io/s/03-link-compenet-reloaddocument-ls3hfy?file=/src/components/Navbar.js]

replace

The replace props is used to replace the current history within the history stack with the previous history. For example, assuming the last page you visited is the “current history” and the page you visited before the current history is the “previous history”, the replace props navigate back to the previous history instead of the current history.

To specify the replace prop apply it to the <Link> Component like so 👇

<Link to="/" replace>Home</Link>
Enter fullscreen mode Exit fullscreen mode

%[https://codesandbox.io/s/04-link-compenet-replace-cntlw4?file=/src/components/Navbar.js]

In other to understand how the replace prop works, two navbar is provided.

Starting from the “red navbar”, here the replace prop is omitted.

  • Click on the blog link,

  • Then click on the content link

  • and then click the home link.

Once you’ve done this, click the back button on the browser. This should return you to the content page. This is the default routing behavior and specifying the replace props should change this.

Starting from the “blue navbar”, here the replace prop is specified.

  • Click on the blog link,

  • Then click on the content link

  • and then click the home link.

  • Then click the back button on the browser

This will return you to the “blog page” instead of the “content page”.

preventScrollReset

The preventScrollReset props (property) returns a boolean and is used to set the browser scroll position from the default behavior of always going back to the top of the page when a link is clicked.

The preventScrollReset props work with Component. To use the preventScrollReset import the <ScrollRestoration> Component as indicated below.

import { ScrollRestoration, Link, Outlet } from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

Then add it to the Link Component as indicated below

<Link to="/" preventScrollReset>Home</Link>
Enter fullscreen mode Exit fullscreen mode

See Navbar.js page on Codesandbox below

%[https://codesandbox.io/s/05-link-compenet-reventscrollreset-lz7xny?file=/src/components/Navbar.js:145-184]

Click on the home link then click the blog link, then click the home link again. Notice how the page remains the same. This does not work for the back or forward button on the browser.

relative

The relative props (property) is used to set the relative route of the <Link> Component.

It takes two values which determine how the relative route is handled.

  • route (default)

  • path

To specify the relative prop apply it to the <Link> Component like so 👇

  <Link to="." relative="path">blog1</Link>
    <Link to=".." relative="route">blog2</Link>
Enter fullscreen mode Exit fullscreen mode

state

The state props (property) is used to set state value on the <Link> Component that can be accessed when the link is clicked.

To access the state value, the useLocation hook is used.

To specify the state prop apply it on the <Link> Component like so 👇

import { Link, useLocation } from "react-router-dom";

<Link to="/" state=" Hello">Home{location.state}</Link>
Enter fullscreen mode Exit fullscreen mode

See the Navbar.js file on Codesandbox.

%[https://codesandbox.io/s/06-link-compenet-relative-9c34pm?file=/src/components/Navbar.js]

click on the home button on the navbar to display hello text

Parsing Attribute on the Link Component

The <Link> Component returns the <a> element. This also means it can accept the same attribute as the <a> attribute.

To specify the HTML attribute, apply it on the <Link> Component like so 👇

<Link className="card" key={item.id} to={item.src} target="_blank">text</Link>
Enter fullscreen mode Exit fullscreen mode

The code example above demonstrate various ways we can parse attribute into the <Link> Component.

See Codesandbox for a code sample

%[https://codesandbox.io/s/08-link-compenet-a-tag-attribute-956st7?file=/src/components/BlogCard.js]

Conclusion

The <Link> Component in React Router does the same thing as the <a> tag in HTML. With the <Link> Components, we can link and navigate between components in a single page application the same way the <a> tag links web pages together in HTML.

Unlike the <a> tag in HTML, the <Link> Component comes with some additional features that make working with the <Link> Component is preferable in SPA (Single Page Application) such as React.

These features include client-side routing, scroll management using the <ScrollRestoration> Components and more.

Furthermore, if implemented correctly, the <Link> Component can greatly improve users experience.

References

  1. React Router Official Docs

  2. Understanding Links in React.js

  3. Linking to other components with react-router

  4. React Router - Relative Links Example

component Article's
30 articles in total
Favicon
Build a note app with JavaScript component.
Favicon
Key characteristic of Component-Based Architecture
Favicon
React Component Libraries: Overview of 19 Top Libs
Favicon
Styling Components in React 🧢
Favicon
Building a Seamless OTP Input Field in React: A Step-by-Step Guide
Favicon
MithrilJS component with state management
Favicon
[Off Topic] Nano introdução do framework Angular para Devs do back
Favicon
Comparing Vue Component Documentation tools
Favicon
Laravel 11 Custom Component File Structure
Favicon
Building Message Component in Vue3
Favicon
Aplicando paginação em um componente Select
Favicon
How much does it cost to repair an outdoor LED display?
Favicon
Global toast in Vue3
Favicon
Unveiling the Hidden Gem of React: The Power of Compound Components
Favicon
Controlled vs Uncontrolled Components in React
Favicon
React components -(Class component v/s function component)
Favicon
3 Ways to Create React Components with Bit
Favicon
Client or Server component ?
Favicon
Desenvolvimento de Componentes AssĂ­ncronos com Vue.js
Favicon
NAND Flash vs NOR Flash: Differences between them
Favicon
Link Component in React Router
Favicon
Guia de Components - para quem tem pressa!
Favicon
How to exchange data between Angular components
Favicon
Component Testing with Cypress and Reactjs
Favicon
React - Higher Order Components (HOC)
Favicon
How to Create Component Library Like Material UI or Mantine UI?
Favicon
Looking forward to adding Algolia's DOCSEARCH to Mantine DataTable
Favicon
Cypress Component Testing vs React Testing Library - the complete comparison
Favicon
Creating Custom Component for NPS Feedback
Favicon
Maximize your Angular code reusability using <NgTemplateOutlet>

Featured ones: