The React Router is a powerful routing library for developing React projects. It allows you to quickly add views and data streams to your application while keeping pages and urls in sync.
A, install,react-route-dom
Implement it in your project
npm i react-router-dom
Copy the code
To install reacr – the router
Two, write the simplest route
In my project, App is my root component, and I write the basic route in App component, which is written according to the actual project, or in a separate Router component.
index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './views/App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.register();Copy the code
App.jsx :
import React from 'react'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import Home from './Home/Home'
import Login from './Login/Login'
function App() {
return (
<Router>
<Switch>
<Route path="/home" component={Home} />
<Route path="/login" component={Login} />
<Redirect from="*" to="/home" />
</Switch>
</Router>
)
}
export default App
Copy the code
- Introduced in app.jsx
react-router-dom
In the libraryBrowserRouter
Set the alias toRouter
, andBrowserRouter
And then there’s the correspondingHashRouter
.BrowserRouter
Is our most common history route,HashRouter
A hash route is a route preceded by a #. - The react – the router – dom in the library
Route
, two attributespath
andcomponent
Indicates that the matched route ispath
When the component is loadedcomponent
- The react – the router – dom in the library
Switch
.Switch
Indicates that only one route is matched at a timeRoute
Fuzzy matching from the top down (i.e/home
Maybe match at the same time/home/1
and/home/2
), addedSwitch
Only the first matched component is loaded - The react – the router – dom in the library
Redirect
, indicates the redirected route, and has two valuesfrom
andto
.from
Indicates the matched route.to
It is a redirected route - At this point, one of our simplest route implementation is complete, can realize the input
/home
loadingHome
Component, input/login
loadingLogin
Component, and all routes that do not match are redirected to/home
3. Realize route jump and navigation route
Above we implemented the basic routing function, but now we can only type in the browser to jump, we want to have a header navigation in the page, or button click to jump.
Create the Header component:
import React from "react";
import { NavLink } from "react-router-dom";
import './Header.scss'
function Header() {
return (
<div>
<ul>
<li>
<NavLink to="/home/user"> User management </NavLink> </li> <li> <NavLink to="/home/article"</NavLink> </li> </ul> </div>) }export default Header;
Copy the code
- Header component
react-router-dom
theNavLink
, is used specifically for navigation link jump tag, corresponding toLink
. The usage is similar to only oneto
Property indicates which link to click to jump to. NavLink
andLink
The difference is,NavLink
An active style will be added to the matching route. We can customize this style, usually used in the overall header navigation component, etc.Link
No matching routing style, generally used in button click jump etc.
4. Realize multi-level routing nesting
Above we only implemented level 1 routing, but we also want to have level 2 routing in the Home component. How to implement this?
Home components:
import React from "react";
import { Route, Redirect } from "react-router-dom";
import Header from ".. /.. /components/Header/Header";
import User from ".. /User/User";
import Article from ".. /Article/Article";
function Home() {
return (
<div>
<Header />
<Route path="/home/user" component={User} />
<Route path="/home/article" component={Article} />
<Redirect from="*" to="/home/user" />
</div>
);
}
export default Home;
Copy the code
- in
Home
Component introductionreact-router-dom
theRoute
andRedirect
Here we didn’t reintroduceRouter
andSwitch
Because they are inApp
Component, global adaptation. - The usage is the same as before, except that we match the path
path
a/home
Indicates the level-2 routing mode/home/user
- And introduce what we wrote before
Header
The component implements a secondary route jump, and its deeper routes are the same as this one, nested in the child component
Dynamic routing and route parameter transmission
We want to use our dynamic routing to pass parameters in the route jump. It is very simple to define the Route as /home/article/:id followed by: parameter name
Look at an example:
import React from "react";
import { Route } from "react-router-dom";
import Article from ".. /Article/Article";
function Home() {
return (
<div>
<Route path="/home/article/:id" component={Article} />
</div>
);
}
export default Home;
Copy the code
The route is then followed by the passed ID value when jumping
<Link to="/home/article/1"> </Link>Copy the code
Receives the ID value from the dynamic route in the Article component
import React from 'react'
function Article(props) {
console.log(props.match.params.id);
return(<div> article information </div>)}export default Article
Copy the code
At props. Match.params. id, you can receive the value passed to you
But when we want to pass more and more complex parameters in the route this way is very troublesome, we use another way
Route is defined in the usual way
<Route path="/home/article" component={Article} />
Copy the code
Pass parameters when a Link jumps
<Link to="/home/article? a=1&b=2"> </Link>Copy the code
or
<Link to={{
pathname: "/home/article",
search: "? a=1&b=2"}}> Article management </Link>Copy the code
Accept arguments in the Article component
import qs from 'qs'
qs.parse(props.location.search)
Copy the code
Introduce QS module and use qs.parse method to parse parameters
Programmatic navigation
It can be seen that our previous route jumps are all Link and NavLink label jumps. However, in some cases, for example, we will perform some logical judgments before jumping and meet the conditions before jumping, and then we need to use our programmatic navigation.
A component that uses Route will receive three properties: History, location, and match. History is used for programmatic navigation. Location and Match are used for routing information, such as the current pathname and parameters
props.history.push
When a route is redirected, historical records are generated
props.history.push("/home/article")
Copy the code
props.history.replace
When a route is redirected to replace the current route, no historical record is generated
props.history.replace("/home/article")
Copy the code
props.history.go | props.history.goBack
Further | before routing routing step back
Use the React Router in real projects. If you don’t know how to use the React Router, leave a comment below.