React Router v6: A Comprehensive Guide to Page Routing in React
Published: 2024-07-09 15:38:52

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/react-router-v6_1cb0495d0ab8d945567e824b3118343f.jpg" alt="React code in an IDE."/></figure>

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:

- [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [React](https://code.pieces.app/blog/react-19-comprehensive-guide)
- [Node JS](https://nodejs.org/en)


## What is React Router?

React Router is [a library that provides the functionality](https://reactrouter.com/en/main) for client-side routing in React. It’s widely used in building [single-page applications (SPAs)](https://developer.mozilla.org/en-US/docs/Glossary/SPA). 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.
- **<Suspense/>**: 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 <Routes> component replaces the <Switch> 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 <Link> or <Route> for a child route as it automatically takes the URL of the parent route.
- **Improved Redirect Functionality**: Redirects are implemented using the <Navigate> component, replacing `history.push` and `history.replace` as used in v5.
- **<Outlet />**: The `<Outlet/>` 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(
  <BrowserRouter>
    {/* App routes */}
  </BrowserRouter>
);
```

- **Link**: The Link component is used to create links in your application. It is similar to the `<a>` 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 (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </nav>
  );
}

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 <Routes> component replaced the <Switch> 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 (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
}

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@latest
```

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(
   <React.StrictMode>
     <BrowserRouter>
     <App />
     </BrowserRouter>
   </React.StrictMode>
 );
```

[Save this code](https://jamesamoo.pieces.cloud/?p=5fd6469647)

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>
   );
 }

export default Navbar
```

[Save this code](https://jamesamoo.pieces.cloud/?p=177c4cabcd)

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 (
     <div>
         <Navbar />
         <h3>Welcome to the Pieces Tutorial</h3>
     </div>
   )
 }

 export default Home
```

After creating the home page, we’re left with two pages. Let’s create the “About Pieces” page next:

```
import React from "react";
import Navbar from "./Navbar";
const About = () => {
  return (
    <div>
      <Navbar />
      <h3>
        Pieces is your AI-enabled productivity tool designed to supercharge
        developer efficiency
      </h3>
      <h3>Unify your entire toolchain with an on-device copilot</h3>
    </div>
  );
};

export default About;
```

Finally, let’s create our ‘Code Snippet” page:

```
//Snippet.js
import React from "react";
import Navbar from "./Navbar";

const Snippet = () => {
  return (
    <div>
      <Navbar />
      <h3>Code Snippet</h3>
      <h3>Have a full explanation and use case of the code provided</h3>
      <h3>Determine possibilities and limitations of code</h3>
      <h3>Ask specific questions based on the code provided.</h3>
    </div>
  );
};

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 (
    <div className="App">
       <Routes>
         <Route path='/' element={<Home/>} />
         <Route path='/about' element={<About/>} />
         <Route path='/snippet' element={<Snippet/>} />
       </Routes>
     </div>
   );
 }
```

[Save this code](https://jamesamoo.pieces.cloud/?p=c10f408720)

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:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image1_c54aebb79c9d5b3b7c0b73e374c7d90a.gif" alt="The very basic webpage created in this tutorial."/></figure>

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](https://code.pieces.app/collections/javascript), which contains common and helpful snippets in development. This snippet collection removes the need to write code from scratch, saving you time.
1. **Pieces Copilot**: Can’t find your specific use case in the snippets collection? [Pieces Copilot](https://code.pieces.app/blog/maximizing-development-efficiency-with-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.
1. **Community**: Do you have any questions or are you curious to know more about React’s features? The [Pieces Discord community](https://discord.com/invite/getpieces) 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](https://github.com/pieces-app).


## 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!