Step 17: React Router

We can store a setting in the app state to switch between different "views.” For example, we can have a boolean showHomepage and display the homepage when it is “true.” When a user clicks on the edit icon, we can set showHomepage to false so to hide the homepage and show the “edit” page instead.

There is a fundamental issue with this approach. The page URL remains the same when we switch views. The standard practice is to use a different URL when switching from one page (view) to another. Indeed, using URL for navigation is essential for bookmarking pages, among other things such as keeping a browsing history. If switch views by updating app’s state, we would not be able to use the back or forward button to go back and forth between views.

Routing comes into play whenever you want to use a URL to navigate between different pages in your application.

Traditionally, it requires a back-end (web) server to handle routing requests for different pages. For example, when a user visits a URL, the server responds with the HTML file (and associated styling/script files) for the page related to it.

In React apps, we can replicate the same effect by using third-party libraries for routing. A popular choice is react-router, which provides a collection of navigational components for React applications.

The react-router library manipulates and uses the browser's session history to provide a sense of routing!

Let’s add react-router to our app:

yarn add react-router-dom

Next update main.jsx to wrap the App component in a BrowserRouter:

  import React from "react";
  import ReactDOM from "react-dom/client";
  import App from "./App";
  import { MantineProvider } from "@mantine/core";
+ import { BrowserRouter } from "react-router-dom";
	
  ReactDOM.createRoot(document.getElementById("root")).render(
    <MantineProvider withGlobalStyles withNormalizeCSS>
+     <BrowserRouter>
        <App />
+     </BrowserRouter>
    </MantineProvider>
  );

We are ready to use react-router for navigation!