Education

A Quick Guide to React Navigation with React Router

logo

DhiWise

September 30, 2022
image
Author
logo

DhiWise

{
September 30, 2022
}

Routing is the most important feature used to build a web application with React.js, it is almost used by 50% of the React project. React router allows end users to navigate from one URL to another based on the action performed. Also, it enables users to move between components without affecting their state and provides unique URLs for the components. 

In this article, we learn about React Navigation with React router 6.0  in-depth and also explore how its components and hooks work./

So let's get started!

A brief about Navigation in React.js with React Router 6.0

React.js application is built using the various components that work similarly to the JavaScript functions. Navigation in React.js displays UI components through conditional rendering by allowing UI to be in synchronization with the browser URL. 

However, the library does not come with the inbuilt routing mechanism, and here React router comes into the picture.

React router is the standard library for routing in React. In simple words, it is the collection of  React components and Hooks. The routing functionality of React router isn’t only limited to matching a URL to the function or component. 

In fact, React router is all about building a user interface that aims to deliver a better user experience by empowering developers to systematically handle routing in web applications.

Under the hood, React router library is used for three main reasons according to its official docs:

1. Subscribing and manipulating the history stack

Browser keeps track of each location ( i.e where the user is while browsing pages) in the history stack. So, when you click the back button in the browser you can see the browser history stack. With client-side routing with React router developers can manipulate browser history programmatically. 

2. Matching the URL to the routes

During the initial render and on the history stack change, react-router matches the location against the route config and finds out the set of matches to render. 

3. Rendering a nested UI from the route matches

When the route matches with the URL it is represented using a match object. The path name holds the portion of the URL that matches the route. React router creates an array of matches for routes and the URL so it can easily render a nested UI that matches with the route nesting. 

Installing React Router DOM version 6.0

To add React Router 6.0 to your existing React.js project, first install the dependencies using a package manager like npm or yarn. 

yarn add react-router-dom@6

npm install

npm install react-router-dom@6

Now let's look into some of the new features of React Router 6.0

React Router version 6 new features

Till now numerous modifications have been made in the React Router library such as more powerful route patterns matching algorithms and new routing components. On the other hand, the package size is reduced to about 58%. 

The new version of the React Router Dom does not provide a “Switch” to wrap the routes, instead, it provides “Routes” to accomplish the same goal. Similarly, earlier we had to specify the entire path in the Link but now the path of the Link is relative to the route path that rendered it. 

With Nested Routes, you can now nest your routes inside one another and their paths will nest too. And the Route Matching Algorithm enables you to match a route to a certain prop without requiring the exact property. 

In the next section, we will dive deep into the important components and hooks for React routing.

React Router 6.0: Important Components and Hooks

Hooks

React Router comes with a few Hooks that lets you access the state of the router and perform navigation from inside the components.

The following hooks can be used only if you are using the React version 16.8 or above.

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

Let's understand each of them briefly.

1. useHistory

The useHistory book gives you access to the history instances that are utilized to navigate through the web application.

import { useHistory } from "react-router-dom";

function DashboardButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/dashboard");
  }

  return (
    
  );
}

2. useLocation

The useLocation hook returns the location of the object that represents the current URL. It is very useful in a situation where you want to trigger the new page view event using a web analytics tool on the new page load.

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  useLocation
} from "react-router-dom";

function usePageViews() {
  let location = useLocation();
  React.useEffect(() => {
    ga.send(["pageview", location.pathname]);
  }, [location]);
}

function App() {
  usePageViews();
  return ...;
}

ReactDOM.render(
  
    
  ,
  node
);

3. useParams

It returns an object with the key/value pair of URL parameters. It is used to access the match.param of the current <Route>.

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return 
Now showing post {slug}
; } ReactDOM.render( , node );

4. useRouteMatch

The useRouteMatch works similar to the <Route>  works and is useful for getting the match data without rendering <Route>

The hook either takes no argument and returns the match object or takes a single argument identical to the props argument of matchPath

import { useRouteMatch } from "react-router-dom";

function LatestNews() {
  let match = useRouteMatch("/news/:slug");

  // Do whatever you want with the match...
  return 
; }

Components

1. Browser Router

Browser router is used if you are using a dynamic server with dynamic URLs. It is a <Router> that uses HTML5 history API (i.e pushState, replaceState and popstate event) and React Context to keep UI in sync with the URL. 

The History library helps React Router keep track of browsing history using a built-in history stack in the browser and the React Context helps to provide history whenever React Router needs it.

While using React Router always make sure that you wrap your application inside of the BrowserRouter component.

import ReactDOM from 'react-dom'
import * as React from 'react'
import { BrowserRouter } from 'react-router-dom'
import App from './App`


ReactDOM.render(
 
   
 
)

2. Hash Router: 

If you are using a server that serves static files then you should use the Hash router component.  The <Router> uses the hash portion of the URL (i.e window.location.hash) to keep your UI in sync with the URL.


  

3. Route

The component has a basic responsibility to render some UI when the path matches the current URL. The Route component allows you to easily map your application location to different React components. Consider an example where you want to render a news component whenever a user navigates to the path “/news”

So you will render the Route path as: 

} />

With Route you can render as many routes as you wish, also you can render the nested routes.

4. Routes

What if you want to match multiple routes to a single URL? Routes can help you to do that. 

Whenever you have more than one Route then you might want to wrap them in the Routes. You can do so by importing Routes from React-router-Dom. 

import { Routes, Route } from "react-router-dom";
function testApp() {
 return (
   
 } />
     } />
     } />
     } />
   
 );
}

5. Link

Next, how should you navigate between the app’s location? The link component is meant for that. It provides you declarative accessible navigation around your application.  

With Link you can also pass an object with properties and function to which the current location is passed as an argument and it returns a location representation as a string.

// passing an object

// Passing a function

 ({ ...location, pathname: "/courses" })} />

6. NavLink

It is a special version of <Link> that knows whether or not it is “active”, also it allows you to add a styling attribute to the rendered element when it matches the current URL.

In React Router 6.0, activeClassName will be removed and you need to use the function className to apply class name to either active or inactive NavLink components.


    "nav-link" + (!isActive ? " unselected" : "")
  }
>
  FAQs

7. Navigate

In the React Router 6.0 Redirect component was removed and replaced with the Navigate component.  The component just acts like a Redirect component by navigating you to the new location and overrides the current location in the history stack. 

import { Navigate } from 'react-router-dom';

 } />

Summing Up:

React Router is the popular, declarative component-based, client and server-side routing library for React. In the article, we have learned about the React router with its components and hooks and how it enables you to update and navigate through the user navigation history. 

If you are building a web application with React.js and want to accelerate the application development process  for you and your team try DhiWise React Web Builder.

The app builder provides you with everything to build a reliable and scalable web application faster. Sign up now to experience its capabilities.