Skip to content

Routing with react router

Luke Deen Taylor edited this page Oct 19, 2019 · 2 revisions

react-router handles routing for the app, which allows different pages to display at different URLs in the app.

Terminology

  • routes are URLs within in the app. If the app was at www.tutv.example, the route “/catalog” would refer to www.tutv.example/catalog, and / would refer to www.tutv.example.
    react-router allows us to have different components appear in the app for different user-defined routes.

Page components

With react-router, each page of the app is a React component. To keep things organized, components for pages are kept in the pages folder (src/frontend/src/pages), separate from the reusable components in the components folder. Pages aren't functionally any different from normal react components, though, except that they're rendered by react-router automatically at certain routes in the app.

Routes

To tell react-router which components should appear at which routes, we define routes inside a <Switch> component in App.tsx. Here’s an example configuration:

<Switch>
  <Route path="/catalog">
    <Catalog/>
  </Route>
  <Route path="/">
    <Home/>
  </Route>
</Switch>

This configuration tells react-router to render the <Catalog/> component at the /catalog route, and the <Home/> component at the base route.

Note on route precedence

In this example configuration, it is significant that the / route is defined below the /catalog route. When react-router matches a route to a component, it goes through the defined <Route>s in the order they were defined, and stops as soon as it reaches a match. Since /catalog begins with /, if the / route were defined first, react-router would see this route as matching for all routes and stop there, meaning we could never see a separate route defined at /catalog. Similarly, if we wanted to define a route /catalog/asdf, this route would need to be defined before the /catalog route in order to match as intended.

Conclusion

For more on react-router and its other features, see the official documentation.