Routing In React Explained -React Router v6 Tutorial

Sofiyat Aminu
5 min readNov 23, 2021

--

Routing is an important aspect of developing Web Applications. It is the process of navigating through various parts of an application through links. It plays an important role because the URL path determines what would be displayed on the page.

Before the adoption of Single Page Applications, we navigate through different parts of a website by entering a URL, that sends a request to the server. The server then responds by returning the HTML page containing the data we need. So, If we have multiple pages and links, navigating to each of them would require a brand new request to the server.

In React Applications, we do not do things this way. We send a request to the server, this request returns an empty HTML page and the compiled JavaScript files that control our React Application. React then injects the various components that we create into the HTML page. To navigate to various parts of the App, the React Router checks the URL and renders the required data that matches the request.

In this article, we’re going to learn how to use the following;

  • react-router: The library that handles routing in our React Application
  • react-router-dom: This handles routing in the DOM

Getting Started With react-router

To use react-router in our Application, we need to install the react-router library, but since we’re focused on web applications in this article, we’ll install react-router-dom, a variant of the library that enables routing in web applications.

npm install react-router-dom@6 
yarn add react-router-dom@6

Once the react-router-dom is done installing, the next step is to import the necessary components from the library.

Browser Router

The first thing we need to import is the BrowserRoutercomponent and wrap it around our whole application. This gives the app component and its children access to the Router APIs. In the code snippet below, we’re importing it as Router. We’re re-naming it to make it simpler for us to write.

The BrowserRouter component connects your app to the browser’s URL -React Router

import { BrowserRouter as Router } from ‘react-router-dom’;
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import App from ‘./App’;

ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root'));

Links

In order to add navigation in our app, we import the Linkcomponent. This works similar to the HTML anchor tags <a>. With anchor tags, the page refreshes whenever we click on the link, but using the Link component, react-router prevents that from happening. The Link component has a to prop that specifies where we’re navigating to. Let’s take a look at a simple Header component below;

import React from 'react';
import { Link } from 'react-router-dom';

export function Header() {
return (
<Header>
<nav>
<Link to="/home"> Home </Link>
<Link to="/about"> About </Link>
<Link to="/contact"> Contact</Link>
</nav>
</Header>
)
}

Here, each Linkcomponent takes us to its specified URL path.

Routes

The Routes component is an upgrade from the Switch component in the previous versions of the library. We nest all our routes inside this component. All Routes and Link inside the Routescomponent is relative.

Routes are chosen based on the best match instead of being traversed in order. This avoids bugs due to unreachable routes because they were defined later in your <Switch>-react-router

Route

We set up our routes in the Routecomponent. This component takes a path and elementprop. We pass the path we want to visit inside the path prop and the element prop takes in the component we want to render on that page. We can also pass plain HTML elements into the element prop. Let’s take a look at the code snippet below;

import {
BrowserRouter,
Routes,
Route,
} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users" element={<Users />}/>
<Route path="/products" element={<Products />}
<Route path ="/" element={<Outfits/>}/>
<Route path="/footwear" element={<Footwears/>}/>
</Route>
<Route path="*" element={<div>No page found</div>}/>
</Routes>
</BrowserRouter>
export Default App;

So here, when we visit the root Url, we see the Home page, and when we visit, ‘/users’ we see the Users page. The Route component also lets us nest routes within a page. This allows us to have a parent component that controls the rendering of its child components. So, when we visit the products page, the <Outfits/> component is rendered because its path is relative to the parent component, and when we visit the ‘products/footwear’ , the Footwears component is rendered. Also note that for us to correctly render routes, we need to import and render an <Outlet/> component inside the parent component containing the nested routes.

useParams Hook

useParams is a hook that lets us render dynamic params our routes may have. It helps us to access the URL parameters from a current route.

It is very useful in case you want to make an Individual product page for products in an Ecommerce App.

Below is a simple implementation on how to use useParams to access the URL params. For example, lets t;

<Route path="/products/:id" component={Products} />

We can access the id of each product by using the UseParams() hook.

import React from "react";
import { useParams } from "react-router-dom";
export default function Products() {
const { id } = useParams();
return (
<div>
<h1>User id is {id}</h1> </div>
);
}

In the above code, we imported the useParams() hook from the react-router-dom package.

Inside the Products function, we invoked a useParams() hook that returns an object of all the params in the URL. The object is a key and value pair where the key is the idand the value is whatever we pass after /products/

useNavigate Hook

useNavigate()is a hook that gives us access to the navigation object. It is a replacement for the former useHistory hook.

It’s useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.- react navigation

Let’s take a look at how we can apply it here;

import react from ‘react’
import {useNavigate} from 'react-router-dom'
function Users(){
let navigate= useNavigate();
return (
<div>This is a list of users</div>
<button
onClick={()={
navigate('/about')}}>
About Page
</button>
)
}
export default Users;

In the code above, we import the hook from react-router and save it in a variable. To use the hook, we’ll have to invoke it and pass in the path we want to navigate to. So, when we click on the button, the About page is rendered.

--

--