Using react-router-dom routing in React

Keywords: React npm

Conversion from and ____________; https://www.jianshu.com/p/8954e9fb0c7e

Using react-router-dom routing in React

To realize the jump between pages in a single page application built with React, the first thought is to use routing. In React, two commonly used packages can fulfill this requirement: react-router and react-router-dom. This paper mainly focuses on react-router-dom.

install

First enter the project directory and install react-router-dom using npm:

npm install react-router-dom --save-dev //Here you can use cnpm instead of npm commands

basic operation

Then we create two new pages, named "home" and "detail". Write the following code in the page:

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>go detail</a>
            </div>
        )
    }
}

home.js

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>Go back to home</a>
            </div>
        )
    }
}

detail.js

Then create a new routing component named "Router.js" and write the following code:

import React from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import Home from '../home';
import Detail from '../detail';


const BasicRoute = () => (
    <HashRouter>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </HashRouter>
);


export default BasicRoute;

For example, the code defines a pure routing component, which wraps two page components, Home and Detail, using Route components, and applies Switch as routing matching. When the routing component detects that the address bar matches Route's path, it automatically loads the response page.
Then in the entry file, which I specify here is index.js, write the following code:

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';

ReactDOM.render(
  <Router/>,
  document.getElementById('root')
);

This is equivalent to returning a routing component to the page. Let's run the project first to see the effect and enter it in the address bar.“ http://localhost:3000/#/":

home.js

Input“ http://localhost:3000/#/detail":

detail.js

Jump through label a

As you can see, the routing is already working. Next, let's do the jump between pages. In home.js and detail.js, we modify the following code:

import React from 'react';


    export default class Home extends React.Component {
        render() {
            return (
                <div>
                <a href='#/ detail'> go detail</a>
            </div>
        )
    }
}

home.js

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a href='#/'> Back to home</a>
            </div>
        )
    }
}

detail.js
Repackaged and run, enter in the browser address bar“ http://localhost:3000/ Try to see if the page can jump properly. If not, check the code step by step for errors. The above is the use of href tag a to jump between pages, in addition to react-router-dom also provides a way to jump through the function of the page.

Jump through a function

First, we need to modify two codes in router.js:

...
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom';
...
<HashRouter history={hashHistory}>
...

Then in home.js:
import React from 'react';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/ detail'> go detail</a>
                <button onClick={() => this.props.history.push('detail')}>Jump through a function</button>
            </div>
        )
    }
}

Add a button under the a tag and an onClick event to jump to the detail page through this.props.history.push function. The code added to the routing component is to register history as an object in the props of the component, and then you can call history's push method to jump the page through props in the subcomponent.

In many scenarios, we also need to pass parameters while jumping the page. In react-router-dom, we also provide two ways to pass parameters.

url data transmission

In router.js, modify the following code:

...
<Route exact path="/detail/:id" component={Detail}/>
...

Then modify detail.js and use this.props.match.params to get the parameters passed by the url:

...
componentDidMount() {
    console.log(this.props.match.params);
}
...

Enter in the address bar“ http://localhost:3000/#/detail/3 Open the console:

You can see that the passed id=3 has been obtained. react-router-dom matches the parameters passed by the url by "/:".

Implicit Reference Transfer

In addition, the push function can also be used to transfer parameters implicitly.

Modify the home.js code as follows:

import React from 'react';


export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/ detail / 3'> to detail</a>
                    <button onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        }
                })}>Jump through a function</button>
            </div>
        )
    }
}

In detail.js, you can use this.props.history.location.state to get parameters passed from home:

componentDidMount() {
    //console.log(this.props.match.params);
    console.log(this.props.history.location.state);
}

After the jump, open the console and you can see that the parameters are printed:

Other functions

replace

In some scenarios, repeated use of push or a tag jumps can create a dead cycle, and react-router-dom provides replacement to avoid this. Use replace to jump where a dead cycle may occur:

this.props.history.replace('/detail');

goBack

When you need to return to the higher page in the scenario, use:

this.props.history.goBack();

summary

This article basically covers most of the react-router-dom usage, and I will continue to add any omissions later.



Author: aimmarc
Link: https://www.jianshu.com/p/8954e9fb0c7e
Source: Brief Book
The copyright of the brief book belongs to the author. For any form of reprinting, please contact the author for authorization and indicate the source.

Posted by garethdown on Wed, 24 Jul 2019 22:28:43 -0700