React Router
React is a library for creating User Interfaces, not a full, batteries-included framework. You'll have to supply your own batteries such as a router for URL and link handling.
React Router
React Router is a package that allows us to change the URL, making it look like the user is visiting different pages, when they are actually still on the same page. This is a common pattern in Single-Page Applications (SPAs).
It takes care of two tasks that are traditionally accomplished by going to different pages:
It keeps track of what is supposed to happen and which components should be rendered when you visit specific URLs.
It updates the browser's history with those URLs.
The second piece happens automatically; the first part is what you have to set up. Setting up routes for React Router is very similar to setting up routes in Express and Flask. You define the same basic things: the path, and what should happen when that path is visited. The only difference is that it will do the routing on the client, without actually hitting your server.
Setting Up React Router
Install the react-router-dom
package:
We usually want our whole app to be managed by React Router so we wrap our App
component in a BrowserRouter
component.
main.jsx
To define routes:
App.jsx
Linking to Routes
Link
App.jsx
NavLink
NavLink
s are similar to links but with the added feature of setting an 'active' CSS class on itself if its route is the current one.
App.jsx
404 Routes
Nested Routes
With React Router, we can route users not just page to page but to specific fragments of UI in the same page using nested routes.
Define nested routes for /settings
:
Add an Outlet
component to tell React Router where in the parent component (SettingsIndex
) to render the child:
Dynamic Routes
We can also define dynamic routes with React Router much like Express' and Flask's router.
To access the dynamic URL param
value in the component, we use the useParams
hook:
We can then link to a specific user profile page via the username:
Last updated
Was this helpful?