Routing with react router - JumboCode/TUTV GitHub Wiki
react-router is the tool that handles routing for the app, which allows different pages to display at different URLs in the app.
-
routes are URLs within in the app. If the app was at
www.tutv.example, the route “/catalog” would refer towww.tutv.example/catalog, and/would refer towww.tutv.example.react-routerallows us to have different components appear in the app for different user-defined routes.
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.
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.
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.
For more on react-router and its other features, see the official documentation.