M07 - React Router
Introduction
React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.
Installation
Use below command install React Router to your React application:
1 |
|
Basic use case
Use BrowserRouter
in your index.js
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
And add Routes
to your application different pages in App.js
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Route components can be defined inside your App.js
or use separated files.
Home
1 2 3 4 5 6 7 8 |
|
About
1 2 3 4 5 6 7 8 |
|
Test your application and click About
and Home
links to change visible page. Note how web browser's URL location changes between http://localhost:3000/
and http://localhost:3000/about
.
Note
You can use Link
element to define links to another pages.
Router Hooks
React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components. You can access history, location and parameters via hooks with easy and elegant way.
useLocation
The useLocation
hook returns the location object that represents the current URL.
Modify About
function to show current location.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
useNavigate
The useNavigate
hook returns a function that lets you navigate programmatically.
Modify About
function to use useHistory hook.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Save your project and it should render a Home page first. Click About link and it will render a Button element. Click it and you should see Home page again.
useParams
useParams
returns an object of key/value pairs of URL parameters.
1 |
|
Create a new User
function. Find user name from the incoming parameters.
1 2 3 4 5 6 7 8 9 |
|
Modify your app routes to use User
function in routes and pass hardcoded name to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Save your project and it should render a Home page first. Click User link and it will render a User page with the name.
Example : products
This example will load products from https://dummyjson.com and store loaded products to Redux productsSlice
. First all products will be shown with Products.js
(this is a default route). Product details will be shown with Products.js
when user clicks one of the products. This is done by changing the route of the application.
Files:
index.js
configure Redux store and browser routerApp.js
define routes to products and productProduct.js
show product detailsProducts.js
show all productsproductsSlice.js
store products data