Introduction to React Router
React Router is a powerful tool that allows you to connect the URL of your React app with its corresponding components. It is considered the go-to routing library for React and is widely used in many projects.
Installation
To install React Router using npm, run the following command:
1 | npm install react-router-dom |
Components
The main components you will work with in React Router are:
BrowserRouter
: This component serves as the wrapper for all the Route components in your app.Link
: The Link component is used to create links to different routes in your app.Route
: The Route component is responsible for rendering the components associated with specific routes.
BrowserRouter
To use React Router in your app, you need to wrap your app with the BrowserRouter component. Here’s an example of how to do it:
1 | import React from 'react'; |
Note that the BrowserRouter component can only have one child element, so you should wrap all your app components inside a <div>
.
Link
The Link component allows you to create links to different routes in your app. Here’s an example:
1 | import React from 'react'; |
Route
The Route component is where you define what components should be rendered for each route. Here’s an example:
1 | import React from 'react'; |
In this example, the Dashboard component will be rendered when the route is /
, and the About component will be rendered when the route is /about
. Note the use of the exact
attribute to ensure that the route matches exactly.
Access the location data inside a rendered component
You can access the current location data inside a rendered component using the useLocation
hook:
1 | import { useLocation } from 'react-router-dom'; |
Programmatically change the route
You can programmatically change the route inside a rendered component using the useHistory
hook:
1 | import { useHistory } from 'react-router-dom'; |
Match multiple paths
To match multiple paths with a single route, you can use a regular expression in the path
attribute:
1 | <Route path="/(about|who)/" component={Dashboard} /> |
Inline rendering
Instead of assigning a component to the component
property of a Route, you can use the render
prop for inline rendering:
1 | <Route |
Match dynamic route parameter
To retrieve data from a dynamic React Router route, you can refer to this tutorial.
tags: [“react”, “react-router”, “routing”, “web-development”, “front-end”]