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!
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 the 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, the React router library is used for three main reasons according to its official docs:
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.
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.
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.
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
1 yarn add react-router-dom@6
npm install
1 npm install react-router-dom@6
Now let's look into some of the new features of React Router 6.0
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. 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 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.
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.
1 import { useHistory } from "react-router-dom"; 2 3 function DashboardButton() { 4 let history = useHistory(); 5 6 function handleClick() { 7 history.push("/dashboard"); 8 } 9 10 return ( 11
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.
1 import React from "react"; 2 import ReactDOM from "react-dom"; 3 import { 4 BrowserRouter as Router, 5 Switch, 6 useLocation 7 } from "react-router-dom"; 8 9 function usePageViews() { 10 let location = useLocation(); 11 React.useEffect(() => { 12 ga.send(["pageview", location.pathname]); 13 }, [location]); 14 } 15 16 function App() { 17 usePageViews(); 18 return
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>
.
1 import React from "react"; 2 import ReactDOM from "react-dom"; 3 import { 4 BrowserRouter as Router, 5 Switch, 6 Route, 7 useParams 8 } from "react-router-dom"; 9 10 function BlogPost() { 11 let { slug } = useParams(); 12 return
4. useRouteMatch
The useRouteMatch works similarly 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.
1 import { useRouteMatch } from "react-router-dom"; 2 3 function LatestNews() { 4 let match = useRouteMatch("/news/:slug"); 5 6 // Do whatever you want with the match... 7 return
1. Browser Router
The 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.
1 import ReactDOM from 'react-dom' 2 import * as React from 'react' 3 import { BrowserRouter } from 'react-router-dom' 4 import App from './App` 5 6 7 ReactDOM.render( 8
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.
1 undefined
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:
1 undefined
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.
1 import { Routes, Route } from "react-router-dom"; 2 function testApp() { 3 return ( 4
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.
1 undefined
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.
1 // passing an object 2
1 // Passing a function 2 3
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.
1 undefined
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.
1 import { Navigate } from 'react-router-dom';
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.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.