Client Side Routing 🖥 💻

✅ Objectives

  • Understand the difference between server side routing and client side routing
  • Create a multi-page SPA
  • Utilize the most common react-router components to build a SPA: BrowserRouter, Routes, Route, and Link
  • Use custom hooks like useParams and useHistory to access the state of the router
  • Use the history object to navigate pages
  • Create dynamic routes and use params

How Does Server-Side Routing Work for Non-React Websites?

non-react-request

  • In server-side routing, each click on a link results in the browser fetching and rendering a new webpage, as the server generates the complete HTML page required for each route.
    1. Enter the URL in the address bar and press enter.
    1. The browser sends a request to the server.
    1. The server processes the request.
    1. The server generates a response containing the relevant HTML content along with CSS and JS files.
    1. The browser displays the content retrieved from the server.
    1. When a user clicks a new link, such as the about page:
    • 6-1. The browser sends a new request to the server.
    • 6-2. The server responds with the necessary HTML, CSS, and JS resources for the about page.
    1. The cycle continues

How Does Client-Side Routing Work in React Applications?

react-request

  • Advantage: Faster performance. No Full Page Reload: the page doesn’t undergo a full reload. Only the necessary components and data are swapped out, resulting in a smoother and faster user experience.

  • Through client-side routing, the web app downloads, processes, and displays fresh data seamlessly.

  • Step 1: The browser initiates an HTTP request.
  • Step 2: In response, the server provides the HTML, JavaScript, CSS, and the React JS Bundle. This marks the point where React and React Router assume full control of the application’s behavior.
  • Step 3: The initially received HTML page is almost devoid of content.
  • Step 4: React dynamically injects content by employing components.
  • Step 5: Upon a user’s click on a link:
    • Step 6: React Router takes on the responsibility of handling the request and embedding the appropriate component within the browser.

💡 What is client side routing ?

“Client side routing is a type of routing where as the user navigates around the application or website no full page reloads take place, even when the page’s URL changes. Instead, JavaScript is used to update the URL and fetch and display new content” - Will Taylor

💡 What is React Router?

“React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.” React Router Docs

⬇️

🗒️ Planning Routes

  • Before we do anything, we need to make a plan about what we want.

  • What URLs do we want our application to have to simulate the feeling of different “pages”?

Conventional RESTful principles in mapping URL route

ComponentUrl
Home/ (root route)
ProjectForm/projects/new
ProjectEditForm/projects/:id/edit
ProjectDetail/projects/:id
ProjectList/projects

The Primary React Router Components

  • BrowserRouter

  • Routes

  • Route

  • Link

import React from "react";
import "./index.css";
import App from "./App";

import * as ReactDOM from "react-dom/client";

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

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

1️⃣ BrowserRouter

  • 💡 BrowserRouter is a wrapper for App to allow conditional rendering based on the URL

  • ❓ Where does it belong?

  • Since App component is imported and mounted inside the Index.js file, this is a great place to wrap the component within BrowserRouter

routes

return (
          <Routes>
              <Route path="/" 
                     element={<Home />} />
              <Route path="/projects" 
                     element={<ProjectList
                              projects={projects}
                              />} />
              <Route path="/projects/new" 
                     element={<ProjectForm 
                              onAddProject={onAddProject} />} />
          </Routes>
  );

Routes Component

  • 💡 Routes is a wrapper for Routes. Looks through all its child Route components and returns the one that matches the current URL

route

return (
          <Routes>
              <Route path="/" 
                     element={<Home />} />
              <Route path="/projects" 
                     element={<ProjectList
                              projects={projects}
                              />} />
              <Route path="/projects/new" 
                     element={<ProjectForm 
                              onAddProject={onAddProject} />} />
          </Routes>
  );

Creating routes using the Route Component

  • 💡 Route wraps content that should be visible when the designated route is active.

❓ Where does route belong?

  • Every component nested inside of the Routes component will be individually wrapped inside of a Route component.

  • 💥 Route will be provided a path prop. This is where the developer can define the URL associated with the component. That means that if the pattern of the URL matches the path defined, the component will render

Replace the anchor tags in the Header Component

        <a className="button" href="/projects">
          View All Projects
        </a>
      <Link to ="/projects"
            className="button" >
        View All Projects
      </Link>
  • 💡 Link creates an anchor tag in your application that will navigate using React Router instead of the browser default

  • We want to use Link for navigation in our application. It will ensure that a page reload does not occur, unlike the use of an anchor tag <a></a>

  • 💥 Link will be provided a to prop which indicates where the link should navigate to (generates the href)

useParam hook

import { useParams } from "react-router-dom";
const ProjectDetail = () => {
  const { id } = useParams()
  //use parameter
  //For example, if the URL is: localhost:3000/projects/18
  // id will be 18
  return (
    <h1>
      {id}
    </h1>
  )};

useParam hook

The useParam hook retrieves the route parameter from the URL. This allows us to access /:id, which represents dynamic values embedded within the URL, and is often used to identify specific resources.