React-router easy to use

How to achieve multi-page jump in the react single-page application.
The general application of page jump is a very simple and easy things, but the link changes can be achieved.React-router in React has a third-party library that can help us to achieve multi-page jump.github link is React-router.Now I simply use react-router to achieve a simple example of the use.

1、First, let's create a react application using create-react-app

Install create-react-app

npm install create-react-app -g

Create a application with create-react-app

create-react-app demo1

You can go to demo1 and run yarn start to run our application

The application demo1 directory structure is as follows:

2、 install React-router

npm install react-router-dom --save-dev

3、 create a few pages, below I simply create Home, About, Details page

In the App we use React-router

Modify the App.js file.The code as follows:

import React, { Component } from 'react';
import { Route, Switch,BrowserRouter } from 'react-router-dom';

import Home from './home';
import About from './about';
import Details from './details';

import './App.css';

class App extends Component {
  render() {
    return (
        <BrowserRouter basename="/">
            <div>
                <div className="nav">
                    <a href="/">Home</a>
                    <a href="/about">About</a>
                    <a href="/details">Details</a>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}  />
                    <Route exact path="/about" component={About}  />
                    <Route exact path="/details" component={Details} />
                </Switch>
            </div>
        </BrowserRouter>
    );
  }
}

export default App;

Browse our application http: // localhost: 3000 in your browser.
The final application as shown:

image--2-

Click different link will enter to the corresponding page.

Look, using React-router is so easy.Now, you can try it by yourself。

React-router there are many powerful features. You can consult the official React-router documentation to use other properties and functions.

Show Comments