DEV Community

Vikraman
Vikraman

Posted on

Exploring React Router 6

Working of the React Router 6

Introduction

Single-page applications (SPAs) with multiple pages need to have a mechanism of routing to navigate between those different views without refreshing the whole webpage. We can dynamically change application views by switching the app state with conditional rendering, but in most scenarios, we need to sync the application URL with views.

What is React Router?

React Router is a complete solution that can help in routing activities within React applications. This feature comes with pre-built components, hooks, and helper functions which are essential when coming up with up-to-date formation strategies. React Router project has come up with two different packages that will help you integrate routing either in your web app or any other app that uses React.

React Router v6 includes modern features such as relative nested routes, optimistic UI, and developer-friendly hooks.

Why do we use React Router for routing?

Traditional web applications with multiple pages commonly have several separate files that display different views, but modern single page applications (SPAs) use video-like scenes. This makes it necessary to use routing in order to switch between different URLs. For any React application requirement, you don’t always need an external library but with regards to routing, this may not be true, routing needs are complex and you must use a router library to meet them.

React Router is the most popular and feature-rich routing library for React-based SPAs. It has a small footprint, a simple API, and well-written documentation, allowing any React developer to implement routing productively in any React app.

BrowserRouter

The BrowserRouter serves as a container which envelops the entire application and manages the routing within. In this case, you can define routes, switch between them, and interact with different URL paths in single-page application (SPA) mode but with no need for excessive page reloading.

Routes

Routes is an element container that displays the first child route that matches the current location. This has replaced the previous Switch component and provides a way to group all route definitions together.

Route

Used to define individual route. Each individual Route component specifies a path and the component to render when the URL corresponds to that path. The path prop defines the URL path, and the element prop specifies the component to render.

export default function App() {
  return (
    <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/user/:username" element={<User />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
    </BrowserRouter>
  );
}


Enter fullscreen mode Exit fullscreen mode

Let's work on the application.

First, let's set up a new React application. If you haven't already, install Node.js and npm. Then, create a new React app using Create React App:

npx create-react-app react-router-example
cd react-router-example

Enter fullscreen mode Exit fullscreen mode

Next, install React Router:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Creating Components

We'll create four components for our example: Home, About, User, and NotFound.

  • Home will serve as the landing page and provide navigation links.
  • About will display some information about the application.
  • User will display user-specific information based on the URL parameter.
  • NotFound will be a fallback component for any unmatched routes.

Let's start by creating these components.

Home Component

Create a file named Home.js inside the src/components directory and add the following code:

import React from 'react';
import { Link } from 'react-router-dom';
import './Home.css';

const Home = () => {
  return (
    <div className="home">
      <h2>Home Page</h2>
      <nav>
        <ul>
          <li><Link to="/" end>Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/user/john">User John</Link></li>
          <li><Link to="/user/jane">User Jane</Link></li>
        </ul>
      </nav>
    </div>
  );
};

export default Home;

Enter fullscreen mode Exit fullscreen mode
Link

The Link component helps build interactive links in React applications for navigating to other routes without refreshing the page so that your app can function like a single page application (SPA).

  • β€œto” Prop should be set as the route to follow when navigating. It can either be a single path in a string form or an object for advanced navigation that includes state or search params.
  • When a hyperlink is clicked, it renders the new component without reloading the entire page
About Component

Create a file named About.js inside the src/components directory and add the following code:

import React from 'react';

const About = () => {
  return (
    <div>
      <h2>About Page</h2>
      <p>This is the About page of our React Router example.</p>
    </div>
  );
};

export default About;

Enter fullscreen mode Exit fullscreen mode

User Component
Create a file named User.js inside the src/components directory and add the following code:

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

const User = () => {
  const { username } = useParams();

  return (
    <div>
      <h2>User Page</h2>
      <p>Username: {username}</p>
    </div>
  );
};

export default User;
Enter fullscreen mode Exit fullscreen mode
useParams

useParams is a hook that enables you to get the dynamic parameters of the current route, which are usually defined in the route paths and later used to capture URL values.

  • The part of the route defined with : (e.g., :id in /user/:id) acts as a placeholder for the dynamic value.
  • Inside the component rendered by the route, use useParams to access these dynamic values.
NotFound Component

Create a file named NotFound.js inside the src/components directory and add the following code:

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

const NotFound = () => {
  return (
    <div>
      <h2>Page Not Found</h2>
      <p>Sorry, the page you are looking for does not exist.</p>
      <Link to="/">Go to Home</Link>
    </div>
  );
};

export default NotFound;

Enter fullscreen mode Exit fullscreen mode
Setting Up the Router in App.js

Now, let's set up the router in our main App.js file. Import the necessary components from React Router and configure the routes.

Update src/App.js with the following code:

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import User from './components/User';
import NotFound from './components/NotFound';
import './App.css';

export default function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <h1>React Router Example</h1>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/user/:username" element={<User />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Enter fullscreen mode Exit fullscreen mode

Running the Application

With everything set up, you can now start the development server to see your app in action:

npm start
Enter fullscreen mode Exit fullscreen mode

Navigate to http://localhost:3000 in your browser. You should see the home page with navigation links. Clicking on the links will take you to the respective pages (About, User, etc.), and if you try to navigate to a non-existent route, you will see the NotFound component.

Top comments (0)