Back

Jul 9, 2024

Jul 9, 2024

React Router v6: A Comprehensive Guide to Page Routing in React

Dive into a comprehensive guide on React Router and how to implement Page Routing inside a React project.

Code in an IDE.
Code in an IDE.
Code in an IDE.

Users can navigate through web pages thanks to a process called routing. Routing in web applications is crucial, as it enables users to access different pages in an application upon request. Because it does not provide its own router, React must be paired with an external library called React Router.

This article will explore React Router v6, its core features, and how to implement it in your projects.

To properly understand how page routing works using React Router, you must be familiar with the following:


What is React Router?

React Router is a library that provides the functionality for client-side routing in React. It’s widely used in building single-page applications (SPAs). React Router's major importance lies in its ability to navigate from one page to another in an application while providing a seamless user experience. With this library, users can navigate to pages on a website without triggering a page reload every time a new page is clicked. This also improves the speed and performance of an application.


Features of React Router

The need for React Router and its importance expands beyond the navigation of web pages. It provides additional helpful features, some of which we will discuss in this section.

  • Client-side Routing: Client-side routing allows users to access content from a web page without an additional server request. This removes the need for a page to reload as its content becomes available immediately after its link is clicked. This is a major upgrade to traditional websites where a page reload is initiated every time a user clicks a link.

  • Dynamic Routing: React React Router adopts the dynamic approach of routing which allows routes to be defined during an application’s rendering state. This leads to faster load times and the development of more complex applications.

  • Redirects: With React Router, you can conditionally navigate to a new route. Redirects allow users to navigate to a new location that overrides the history stack's current location. For example, a login page should redirect to a dashboard page after successful user authentication.

  • : With React suspense in React-Router, you can include a skeleton UI that serves as a placeholder when a new page is loaded or a data fetch process is completed.

  • Error Handling: React Router 6 handles most of the errors in your application, catching errors that are thrown while rendering, loading, or updating data.


What’s New in React Router v6?

In addition to the features discussed above, React Router v6 introduces significant improvements and major breaking changes from the previous versions.

  • Nested Routes: The new version of React Router allows the use of nested routes, a powerful feature used to define a particular route inside another route. This is especially useful in blogs where you need to render multiple components on the same page following a particular sequence. For example, a blog comment component should only be accessed after a particular blog post component has been rendered.

  • Routes Component: The component replaces the component in v6, further simplifying React routing and improving user experience.

  • Smaller Bundle Size: Compared to v5, React Router v6 has a significantly smaller bundle size, which allows developers to build more performant applications.

  • Relative Links: Unlike previous versions of React Router, v6 comes with relative links. This defeats the need for explicitly defining a React Router or for a child route as it automatically takes the URL of the parent route.

  • Improved Redirect Functionality: Redirects are implemented using the component, replacing history.push and history.replace as used in v5.

  • : The component simplifies the logic of implementing nested routes in React Router v6.

  • useParams Hook: This version provides a way to access the dynamic parts of a URL. This is very helpful when working with dynamic URL paths such as fetching data using a user ID or blog posts using a slug.


React Router Components

React Router provides built-in components that allow us to implement page routing. The major components include:

  • BrowserRouter: The BrowserRouter is the parent component that stores other components. It keeps the application’s UI in sync with the URL by storing the current location in the browser’s address bar. Here’s an example:

import * as React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
const root = createRoot(document.getElementById("root"));
root.render(
    {/* App routes */}
);
  • Link: The Link component is used to create links in your application. It is similar to the tag in HTML but does not trigger a page reload when clicked, making it suitable for single-page applications (SPA). Here’s an example:

import { Link } from 'react-router-dom';
function Navigation() {
  return (
Home        
About        
  );
}
export default Navigation;
  • Route: The React route component controls the rendering of web pages by rendering page content if the current URL matches the path specified in the Route component. Here’s how it is used:

<Route path="/" element={<HomePage />} /><Route path="/about" element={<AboutPage />} />
  • Routes: Introduced in v6, the React Routes component contains multiple routes in your application. The component replaced the component used in React Router v5 and older versions.

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
function App() {
 return (
} />        } />          
  );
}
export default App;


Installation

To use the library and improve your routing with Reactjs, you must have React installed and set up on your machine. Follow these steps to get started:

1. Open your terminal and run this command to create a new React project (using Vite):

npm create vite react-router-project react

2. Install the React Router library:

npm install react-router-dom

3. Open your main.js (or index.js) file and wrap your App component in the BrowserRouter component:

import React from 'react';
 import ReactDOM from 'react-dom/client';
 import './index.css';
 import App from './App';
 import reportWebVitals from './reportWebVitals';
 import { BrowserRouter } from 'react-router-dom';
 const root = ReactDOM.createRoot(document.getElementById('root'));
 root.render(
 );

Save this code

Now we’re all set! We can now see how we’ll navigate web pages with the help of the React Router.


Implementing Page Routing with React Router v6

In this section, we’ll look at a practical example of implementing page routing using React Router. Our goal is to navigate between different pages of a web application without triggering a reload. First, we start by creating our Navbar, which will contain our links:

import { Link } from "react-router-dom"; const Navbar = () => {   return (<nav><ul><li><Link to="/">Home</Link></li><li><Link to="/about">About Pieces</Link></li><li><Link to="/snippet">Code Snippet</Link></li></ul></nav>   ); }

Save this code

Here, we have created three links using the Link component from react-router-dom. We can then create the files that contain the pages’ content when the links are clicked. Let’s start by creating a simple component for our Home page:

//Home.js
 import React from 'react'
 import Navbar from './Navbar'
 const Home = () => {
   return (
                  Welcome to the Pieces Tutorial     
   )
 }
 export default Home

After creating the home page, we’re left with two pages. Let’s create the “About Pieces” page neFinally, let’s create our ‘Code Snippet” page:

//Snippet.js
import React from "react";
import Navbar from "./Navbar";
const Snippet = () => {
  return (
            Code Snippet      Have a full explanation and use case of the code provided      Determine possibilities and limitations of code      Ask specific questions based on the code provided.    
  );
};
export default Snippet;

After creating the content for these web pages, we can use the routing functionality offered by the React Router. In your App.js file, import the Routes and Route component from the library:

import { Route, Routes } from 'react-router-dom';
 import './App.css';
 import Home from './Home';
 import About from './About';
 import Snippet from './Snippet';
 function App() {
 return (
                } />         } />         } />            
   );
 }

Save this code

As we explained earlier, the Route components are wrapped in Routes. The element contains the component to be rendered when a path matches a URL. Here’s how the code snippet behaves in our browser:

Interacting with hyperlinks using React Router and Pieces.

We’ve successfully implemented page routing using React js Router! We see that other pages are loaded without triggering a full page reload.


React Router x Pieces: Staying Ahead of the Curve

Are you excited about the React Router update and eager to use it in development? You don’t have to do it alone; Pieces is here to help! Here are three ways Pieces can help you in your journey:

  1. Collections: Stay ahead of coding with the Pieces-curated JavaScript Snippet Collection, which contains common and helpful snippets in development. This snippet collection removes the need to write code from scratch, saving you time.

  2. Pieces Copilot: Can’t find your specific use case in the snippets collection? Pieces Copilot provides contextualized code generation specifically tailored to your codebase. Explore the exciting possibilities of React Router with the help of the Pieces Copilot.

  3. Community: Do you have any questions or are you curious to know more about React’s features? The Pieces Discord community would love to chat! This fast-growing community of friendly developers is eager to learn, help with debugging, and build using exciting languages and the Pieces API.


Conclusion

React Router provides a smooth experience when navigating between web pages, leading to an overall improved user experience. In this blog post, you have learned about React Router and its features, components, and implementation of page routing using it. Further, you learned three key aspects that Pieces can help you with when implementing page routing or throughout your entire development process. Happy coding!

James Amoo headshot.
James Amoo headshot.

Written by

Written by

James Amoo

James Amoo

SHARE

SHARE

Title

Title

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.