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

Pieces šŸŒŸ - Jul 9 - - Dev Community

React 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 <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>
);
Enter fullscreen mode Exit fullscreen mode
  • 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;
Enter fullscreen mode Exit fullscreen mode
  • 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 />} />
Enter fullscreen mode Exit fullscreen mode
  • 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 (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  1. Install the React Router library:
npm install react-router-dom@latest
Enter fullscreen mode Exit fullscreen mode
  1. 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>
 );
Enter fullscreen mode Exit fullscreen mode

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

export default Navbar
Enter fullscreen mode Exit fullscreen mode

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

 export default Home
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
   );
 }
Enter fullscreen mode Exit fullscreen mode

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:

The very basic webpage created in this tutorial.

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .