Exercise 5.2D: React Router

Purpose: Learn to use React Router to navigate instead of the simpler conditional rendering method used earlier. Build on the code you build through Exercise 5.2C.

You may have already noticed some limitations of the conditional rendering method of routing introduced earlier. The point was to take all the navigation, routing, and linking, and push it to the front end, emulating a classic multi-page application while avoiding wasteful server calls and refreshes. Although we were successful in avoiding server calls and emulating the URL bar somewhat, we have not yet achieved these goals. The browser URL bar does not sync consistently with our conditionally rendered routes. There is no back/forward navigation, no bookmarking, no shareable URLs, no history management. It would also be nice to have cleaner-looking code. We might solve these and other problems ourselves, but React Router solves all of these problems and more quite nicely.

Install React Router

React Router requires installation. From your React project root, run the following on the command line:

pnpm install react-router-dom

React Router components need to be imported into code where used:

import {BrowserRouter, Routes, Route, Link, NavLink, useNavigate, useLocation} from 'react-router-dom'

The above import loads all hook functions we will use in this exercise. In your files, import only what is needed.

Setup in main.jsx

React Router has three main components:

Typically, we wrap BrowserRouter in main.jsx around the entire <App> component in it, as follows:

main.jsx

We could do this wrapping in App.jsx instead, but it is considered better separation of concerns to do it in main.jsx.

Basic Routing in App.jsx

Now, we will update App.jsx, Layout.jsx, and Nav.jsx to use React Router. We no longer need the state variable "route", nor to pass the "setRoute" function down to the Layout or Nav components. We will replace the nav links with the <NavLink> component, which fills the same function but integrates with React Router. (there is also a <Link> component that works the same but has a different default style).

App.jsx (Before)
App.jsx (After)
Layout.jsx
Nav.jsx

useLocation Hook

Earlier, we used the Javascript global window.location to simulate routing. React Router comes with a custom hook function, useLocation(), that behaves like window.location, but integrates smoothly with React Router. In the example below, useLocation() is used to add custom page titles and matching headings from the navLinks data in Layout.jsx.

Layout.jsx

useNavigate Hook and Catch-All Routes

The useNavigate() hook allows you to redirect, similar to Flask's redirect() function, except it is entirely on client side. Some oddities are: useNavigate() returns a function meant to be called later, and that function cannot be called directly in the component function. It is normally called inside of useEffect or an event handler. The example below sets up a catch-call route <Route path="*"> and calls on a <Redirect component> that uses useNavigate to redirect any route other than the specified ones to a "/home" route.

App.jsx

The useNavigate() function can also be used to emulate Browser history. If you call n = useNavigate();, then n(-1); emulates the Back button and n(1); emulates the Forward button.

Nesting and Using <Outlet>

Sometimes, you may want to wrap a tag or component around one group of routes but not others. One good example is when you want different navs for different pages.(for example, if admin pages get a different nav than others). Unfortunately, simply wrapping doesn't work, but fortunately, there is a way to do it by wrapping <Route> tags around each other, using their "element" prop, and using an importable component called <Outlet>. The example below adds a secret route (/secret) with a secret nav and a secret message. It modifies the Layout component to receive alternate nav links and use <Outlet> instead of {children}. It also moves the contents of into the component function body due to the way navLinks is now passed. Test by going to the /secret route.

App.jsx (After)
App.jsx (Before)

Optional: Additional Reading on React Router

Nesting can also be used to make subpaths for routes. React Router also supports custom dynamic URLs with parameters, similar to Flask. These features are discussed in this React Router tutorial. Implementing any of the examples is optional, but it may increase your comfort level with React Router.

Next Exercise

Next, in Exercise 5.4, you will connect the contact form to a Flask API. You will also deal with issues that arise when you try to run React Router in prod mode (after running "pnpm run build").