Deep Dive into React Router

Let's uncover everything there is to help you setup routing in react using react router v6.

Deep Dive into React Router

We'll cover the basics of routing in react with react-router-dom, what it offers and different hooks for the same. So, let's get started.

1. Basics

1.1 Installation

Let's first start with creating a simple react application.

npx create-react-app@latest react-router-demo

After the initial project is setup now we can install react-router-dom which is the package used for internal routing in react applications.

npm i react-router-dom

Now that all the installation is covered let's get started with routing

1.2 Browser Router

Browser router is a basically a context in react. And to get started with routing you first need to wrap your <App /> component in BrowserRouter context.

import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
        <App />
    </BrowserRouter>
  </React.StrictMode>,
)

Now that our entire app is covered in the Router context we can create different routes using the Routes and Route hooks provided with react-router-dom.

Let's go to App.jsx and create two rotues

  • Home - "/"

  • blog - "/blog"

import { Route, Routes } from 'react-router-dom'

const App = () => {
    return(
        <div>
            <Routes>
                <Route path="/" element={<h1>Home page</h1>} />
                <Route path="/blog" element={<h1>Blog page</h1>} />
            </Routes>
        </div>
    )
}

The above code created the required routes for us. And is the basic code for setting up routes in react. Let's delve a little deeper.

2. Deep diving

Routers

90% of the time you are going to be using BrowserRouter only, but react router offers other routers as well so let's take a look.

  1. Router

    <Router>is the low-level interface that is shared by all router components.

  2. Browser Router

    We already saw this right?

  3. Hashed Router

    HashedRouteris for use in web browsers when the URL should not (or cannot) be sent to the server for some reason.

  4. Memory Router

    MemoryRouter stores its locations internally in an array.

  5. Static Router

    StaticRouter is used to render a React Router web app in node. Provide the current location via the location prop.

  6. Native Router

    <NativeRouter> is the recommended interface for running React Router in a React Nativeapp.

3.Navigating Between Routes

A <Link> is an element that lets the user navigate to another page by clicking or tapping on it.

<Link> is basically a react equivalent of <a> or anchor tag in html. It offers navigating between pages in internal routing.

Example usage:

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

const LinkDemo = () => {
    return(
        <nav>
            <ul className="alllinks">
                <li><Link to="/"></Link>Home</li> // Route to / - index route
                <li><Link to="/about"></Link>About</li> // link to /about page
                <li><Link to="/contact"></Link>Contact</li> // link to /contact page       
            </ul>
        </nav>
    )
}

3.2 useNavigate Hook

Although link tag can be used when you want to directly create an anchor link but what if you want to route to different page within a function when something happens?

In such cases useNavigate hook comes into play.

import { useNavigate } from "react-router-dom";

function useLogoutTimer() {
  const navigate = useNavigate();

  useEffect(() => {
       setTimeout(() => {
    navigate("/", { state : { someKey : "Value" } } ); // pass a state to the / route when navigating, it's like sending parameters
}, 3000)
, []);

    return (
        <div>
            Routing to home page after 3 seconds
        </div>
    )
}

You can send some data values from page by sending it in state in the navigate object.

How to read the state?

For reading all this state we will use another hook, useLocation.

3.2.1 useLocation() Hook

This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location changes.


import * as React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  let location = useLocation();

  let state = location.state // access a state like this

  return (
    <div>Home page</div>
  );
}

Location object has the following properties

  • hash: of the current URL

  • key: unique key of this location

  • pathname: path of the current URL

  • search: query string

  • state: state value of location create by '<Link state>' or 'navigate'

That wraps up this article on react routing.

Have any doubts? Have any topic that you need covered? Feel like there could be some improvements? Or maybe you just wanna discuss something?

Well, anyway feel free to connect :)