The Reach Router Tutorial: A Quickstart Guide for Routing in React Apps
In my recent project, I used Reach Router as it is the simplest way to implement routing in a React app. It provides an easier alternative to React Router, which I have used in the past. Here is a quick 5-minute tutorial to get started with Reach Router.
Installation
To get started, install Reach Router using the following command:
1 | npm install @reach/router |
In case you are unfamiliar with the @
syntax, it is an npm feature that allows the use of scoped packages.
Next, import Reach Router in your project:
1 | import { Router } from '@reach/router' |
Basic Usage
I typically use Reach Router in the top-level React file, such as index.js
in a create-react-app installation. Wrap all the components that you want to appear inside the Router component:
1 | ReactDOM.render( |
The path
attribute allows you to set the URL path for each component. When you type that path in the browser URL bar, Reach Router will display the corresponding component.
By default, the /
path is the index route and serves as the home page when no specific URL or path is specified beside the app domain.
Setting a Default Route
When a user visits an URL that does not match any defined route, Reach Router will automatically redirect to the /
route by default. To handle this scenario and display a custom “404” message, you can add a NotFound
component with the default
attribute:
1 | <Router> |
Programmatically Changing Routes
For programmatically changing the route in your app, you can make use of the navigate
function from Reach Router:
1 | import { navigate } from '@reach/router' |
Linking to Routes in JSX
To create links to your routes using JSX, you can utilize the Link
component provided by Reach Router:
1 | import { Link } from '@reach/router' |
URL Parameters
You can add parameters to your routes using the :param
syntax:
1 | <Router> |
In the User
component, you can access the userId
parameter as a prop:
1 | const User = ({ userId }) => ( |
Nested Routes
Reach Router allows you to define nested routes by specifying them within a parent route component:
1 | <Router> |
In this example, the /private-area/23232
route would point to the User
component, passing 23232
as the userId
.
Additionally, you can allow a component to define its own routes by using the /*
wildcard after the route:
1 | <Router> |
Inside the PrivateArea
component, you can import Router again and define its own set of sub-routes:
1 | // Import Router inside PrivateArea component |
Any route starting with /private-area/something
will be handled by the User
component, with the remaining part sent as the userId
prop.
To display something in the /private-area
route, you also need to add a /
handler in the PrivateArea
component:
1 | //component PrivateArea |
Tags: reach router, react router, routing in react, react app, react tutorial