Catalogue of this series

  • 01 preface
  • 02 Development environment construction
  • 03 Scaffolding creates projects where everything is a component
  • 04 Basic features JSX, Props, State, Lifecycle, Event, and Style
  • Component rendering control
  • 06 Container components, display components
  • 07 Front-end route react-router
  • 08 State management React-Redux
  • 09 Data request fetch
  • 10 Check the attribute type prop-types

Liking is a virtue:)


React Quick Start -07 Front-end route React-router

The target

  • Based on using
  • Parameter passing
  • Routing matching
  • Convert the animation
  • Hop routing

The environment

  • react 16
  • react-router 4
  • react-router-dom 4
  • react-transition-group

Installation 0.

From the official website, we can find that react-router can be used on the web site side and native device side

We are here for web site side installation

yarn add react-router-dom
Copy the code

React-router packages will automatically rely on installation

1. Run first a simple example

  • The code model
import React, {Component} from 'react'
import {HashRouter as Router, Route, Link, Switch} from 'react-router-dom'

const Home = (a)= > (
  <div>
    <h2>Home page</h2>
  </div>
)
const About = (a)= > (
  <div>
    <h2>about</h2>
  </div>
)

class RouterView extends Component {
  render() {
    return(< the Router > < div > < ul > < li > < Link to = "/" > home page < / Link > < / li > < li > < Link to = "/ about" > about < / Link > < / li > < / ul > < Switch > < the Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </div> </Router> ) } } export default RouterViewCopy the code
  • The code structure

The outermost layer is the

component.

is the content of the component that you see. is the page Link

  • Dynamic diagram

  • codepen

2. Basic use

2.1 BrowserRouterorHashRouter

  • BrowserRouterIt is based on HTML5 pushState and replaceState, many browsers do not support, there are compatibility issues.

Long so http://localhost:3000/about link address

  • HashRouterYes The browser parses the route

The link looks like http://localhost:3000#/about

  • Flexible switch
import {HashRouter as Router, Route, Link, Switch} from 'react-router-dom'
//import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom'

<Router>
  ...
</Router>
Copy the code

I aliased it with as Router for easy switching

2.2 components<Route>attributeexactAn exact match

<Route path="/about" component={About} />
Copy the code

Exact =false path = /about/ about/me

But exact=true only matches path equal to /about

2.3 components<Route>attributestrictMatching of trailing slashes

<Route strict path="/about/" component={About} />
Copy the code

When strict=true, the route request must be followed by a /

2.4 components<Link>

Generate route links

  • attributeto: string

Routing Address String

<Link to="/about? Me = haha "> about < / Link >Copy the code
  • attributeto: object

Route objects

<Link to={{ pathname: '/courses', search: '? Sort =name', hash: '#the hash', state: {fromDashboard: true}> About </Link>Copy the code
  • attributereplace: bool

Set true to replace the browser object history with the current route, and press the back button to see that the previous route has been replaced

2.5 components<NavLink>

Generate route links based on the active style if the current route is set

  • attributeactiveClassName: string

The style name

</NavLink> </NavLink>Copy the code
  • attributeactiveStyle: object

Style object

<NavLink to="/about" activeStyle={{fontWeight: 'bold', color: 'red'}}>Copy the code
  • attributeisActive: func

Judging function

const checkIsActive = (match, location) => { if (! match) { return false } ... Return true} <NavLink to="/about" isActive={checkIsActive}> </NavLink>Copy the code

2.6 components<Switch>

Only the first

or

that matches the currently accessed address is rendered.

Otherwise you have several

will be displayed

2.7 components<Redirect>

Route redirection

<Switch>
  <Redirect from='/users/:id' to='/users/profile/:id'/>
  <Route path='/users/profile/:id' component={Profile}/>
</Switch>
Copy the code

When the /users/:id request is redirected to ‘/users/profile/:id’

  • attributefrom: string

The path that needs to be matched will be redirected.

  • attributeto: string

The URL string to redirect

  • attributeto: object

Redirect the Location object

  • attributepush: bool

If true, the redirection will add the new address to the access history, and there will be no way to go back to the previous page.

2.8 components<Prompt>

Make some prompts when the user leaves the current page.

  • attributemessage: stringSet prompt message when the user leaves the current page.
<Prompt message="Sure?" />
Copy the code

  • attributemessage: func

Callback function set when the user leaves the current page

<Prompt message={location => 'Sure${location.pathname}? `} / >Copy the code

  • attributewhen: bool

Decide whether to enable Prompt

3. Parameter passing

3.1 Writing route definitions

<Route path="/topics/:topicId" component={Topic} />
Copy the code

:topicId Defines a parameter

3.2 Writing the receiving component

const Topic = ({match}) = > (
  <div>
    <h3>Parameters: {match. Params. TopicId}</h3>
  </div>
)
Copy the code

Match. Params is the argument passed

3.3 Complete Examples

code

import React, {Component} from 'react'
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom'

const Topic = ({match}) = > (
  <div>
    <h3>Parameters: {match. Params. TopicId}</h3>
  </div>
)

class RouterView extends Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li>
              <Link to="/topics/rendering">Rendering with React</Link>
            </li>
            <li>
              <Link to="/topics/components">Components</Link>
            </li>
            <li>
              <Link to="/topics/props-v-state">Props v. State</Link>
            </li>
          </ul>

          <Switch>
            <Route path="/topics/:topicId" component={Topic} />
          </Switch>
        </div>
      </Router>
    )
  }
}

export default RouterView
Copy the code

Effect of dynamic figure

4. No match is found

code

import React, {Component} from 'react'
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom'

const Back = (a)= > (
  <div>
    <h2>Home page</h2>
  </div>
)

const NoMatch = (a)= > (
  <div>
    <h2>There is no matching</h2>
  </div>
)

class RouterView extends Component {
  render() {
    return(< the Router > < div > < ul > < li > < Link to = "/ back" > return < / Link > < / li > < li > < Link to = "/ braking/will/not/match" > routing request < / Link > < / li > < / ul >  <Switch> <Route path="/back" component={Back} /> <Route component={NoMatch} /> </Switch> </div> </Router> ) } } export default RouterViewCopy the code

I’ll put a default component at the bottom, which is dead, and that’s it

Effect of dynamic figure

5. Set routine by

Write this in react-route4 nesting

<Switch>
  <Route path="/article" component={ArticleList} />
  <Route path="/article/:id" component={Article} />
  <Route path="/article/:id/recommend" component={ArticleRecommend} />
</Switch>
Copy the code

In a row, the business is as follows

path component instructions
/article ArticleList The article lists
/article/:id Article The article
/article/:id/recommend ArticleRecommend The article recommended

6. Customize routes

Suitable for permission checking

6.1 Creating a CustomRoute

const isAuthenticated = true
const PrivateRoute = ({ component: Component, ... rest }) = >( <Route {... rest} render={props => isAuthenticated ? ( <Component {... props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } /> );Copy the code

6.2 Using a User-defined Route

. <Route path="/public" component={Public} />
<Route path="/login" component={Login} />
<PrivateRoute path="/protected" component={Protected} />
Copy the code

7. Switch animations

I’m using the React-Transition-Group library

Effect of dynamic figure

7.1 installation

yarn add react-transition-group
Copy the code

7.2 Writing animationcss

File fade. CSS

.fade-enter {
  opacity: 0;
  z-index: 1;
}

.fade-enter-active {
  opacity: 1;
  transition: opacity 250ms ease-in;
}

.fade-exit {
  opacity: 0;
}
Copy the code
The name of the instructions
fade-enter Animation start
fade-enter-active Animation activation
fade-exit Animation to leave

For other animation style names, see CSS-Transition

7.3 Importing Packages and Animation Styles

. import {TransitionGroup, CSSTransition}from 'react-transition-group'
import './fade.css'
Copy the code

TransitionGroup, CSSTransition must be imported

7.4 Writing Styles

const styles = {}

styles.fill = {
  position: 'relative'.height: '200px'.width: '500px'} styles.content = { ... styles.fill,top: '40px'.textAlign: 'center'.height: '120px'
}

styles.nav = {
  padding: 0.margin: 0.position: 'absolute'.top: 0.height: '40px'.width: '100%'.display: 'flex'
}

styles.navItem = {
  textAlign: 'center'.flex: 1.listStyleType: 'none'.padding: '10px'
}

styles.hsl = {
  color: 'white'.paddingTop: '20px'.fontSize: '30px'.height: '120px'
}

styles.rgb = {
  color: 'white'.paddingTop: '20px'.fontSize: '30px'.height: '120px'
}
Copy the code

This is the React style object, but you can also write it as a.css file

7.5 Writing a Navigation

const NavLink = props= > (
  <li style={styles.navItem}>
    <Link {. props} style={{color: 'inherit'}} / >
  </li>
)
Copy the code

7.6 Writing presentation components

// Switch area A
const HSL = ({match: {params}}) = > (
  <div
    style={{
      . styles.fill.. styles.hsl.background: `hsl(${params.hThe ${},params.s${} %,params.l`}}} %) >
    hsl({params.h}, {params.s}%, {params.l}%)
  </div>
)

// Switch area B
const RGB = ({match: {params}}) = > (
  <div
    style={{
      . styles.fill.. styles.rgb.background: `rgb(${params.rThe ${},params.gThe ${},params.b`}}}) >
    rgb({params.r}, {params.g}, {params.b})
  </div>
)
Copy the code

7.7 Writing container components

const RouterView = (a)= > (
  <Router>
    <Route
      render={({location}) => (
        <div style={styles.fill}>
          <Route
            exact
            path="/"
            render={() => <Redirect to="/hsl/10/90/50" />}
          />

          <ul style={styles.nav}>
            <NavLink to="/hsl/10/90/50">Red</NavLink>
            <NavLink to="/hsl/120/100/40">Green</NavLink>
            <NavLink to="/rgb/33/150/243">Blue</NavLink>
            <NavLink to="/rgb/240/98/146">Pink</NavLink>
          </ul>

          <div style={styles.content}>
            <TransitionGroup>
              <CSSTransition key={location.key} classNames="fade" timeout={300}>
                <Switch location={location}>
                  <Route exact path="/hsl/:h/:s/:l" component={HSL} />
                  <Route exact path="/rgb/:r/:g/:b" component={RGB} />
                  <Route render={() => <div>Not Found</div>} />
                </Switch>
              </CSSTransition>
            </TransitionGroup>
          </div>
        </div>
      )}
    />
  </Router>
)
Copy the code
  • codepen

code

  • reactjs-example / 5-1-routerBase
  • reactjs-example / 5-2-routerParams
  • reactjs-example / 5-3-routerNoMatch
  • reactjs-example / 5-4-routerTransitions
  • reactjs-example / 5-5-routerRedirect

reference

  • react-router
  • react-transition-group
  • code-splitting-in-create-react-app