[react framework] learning record 12 - learning and use record of react router 6

preface

The code source is the teaching video of shangsilicon Valley in station B, which can be combined with the previous routing articles [react framework] learning record 9- learning how to use react router DOM

The React Router is published to npm in three different packages:

  1. React Router: the core library of routing, which provides many components and hooks.

  2. React router DOM: it contains all the contents of react router and adds some components specially used for DOM, such as < browserrouter >.

  3. React router native: includes all the contents of react router, and adds some API s specially used for ReactNative, such as < nativerouter >.

                              --Shang Silicon Valley md file
    

install

yarn add react-router-dom

Version 6 is installed by default

Select routing mode

history

...
import {BrowserRouter} from 'react-router-dom'

ReactDOM.render(
	<BrowserRouter>
		<App/>
	</BrowserRouter>,
	document.getElementById('root')
)

hash

The usage is the same, just change the label to HashRouter

LInk/routes/route

Put these together. routes replaces the original switch and is mandatory. If you don't write react, an error will be reported.

import {NavLink,Routes,Route} from 'react-router-dom'

<Link className="item" to="/about">About</NavLink>
<Link className="item" to="/home">Home</NavLink>

<Routes>
	<Route path="/about" element={<About/>}/> // Note that the writing of component registration has changed
	<Route path="/home" element={<Home/>}/>
</Routes>

The Route tag supports a property caseSensitive. When it is true, the path of the Route turns on the strict matching mode. The default is false, and the path is case insensitive.

Navigate

Replaced Redirect tag

import React,{useState} from 'react'
import {Navigate} from 'react-router-dom'

export default function Home() {
	const [sum,setSum] = useState(1)
	return (
		<div>
			<h3>I am Home Content of</h3>
			{/* The value of sum determines whether to switch views */}
			{sum === 1 ? <h4>sum The value of is{sum}</h4> : <Navigate to="/about" replace={true}/>}
			<button onClick={()=>setSum(2)}>Point I will sum Change to 2</button>
		</div>
	)
}

There is a replace attribute. When it is true, the push mode becomes replace mode.

Note: when rendering the navigation tag, if the navigation tag is not in routes, it will jump to the corresponding component page instead of rendering as a sub component.

Navlink

Discard the activeClassName attribute and use the className to complete the activation style. You can write a function. The default input parameter is an object with an attribute isActive identifying whether it is activated:

<NavLink
    to="login"
    className={({ isActive }) => {
        console.log('home', isActive)
        return isActive ? 'base one' : 'base'
    }}
>login</NavLink>

If there are multiple NavLink tags, you can write a method and directly execute it in className to achieve the effect of reuse.

Nested routes will be mentioned later. When the NavLink label of the child route is highlighted, the NavLink of the parent route is also highlighted. If the business needs do not need the NavLink of the parent route to be highlighted, you can add the end attribute to the NavLink label of the parent to cancel the highlighting after the child route is matched.

<NavLink to="home" end >home</NavLink>

useRoutes uses routing tables

It is the same as the unified routing management of Vue router.

It can be found in Src / routes / index Create routing table configuration in JS

import About from '../pages/About'
import Home from '../pages/Home'
import {Navigate} from 'react-router-dom'

export default [
	{
		path:'/about',
		element:<About/>
	},
	{
		path:'/home',
		element:<Home/>
	},
	{
		path:'/',
		element:<Navigate to="/about"/>
	}
]

Then, in the component that needs to display the routing component:

import React from 'react'
import {NavLink,useRoutes} from 'react-router-dom'
import routes from './routes'

export default function App() {
	//Generate corresponding routing rules according to the routing table
	const element = useRoutes(routes)
	return (
		<div>
				......
	      {/* Register routing */}
	      {element}
			  ......
		</div>
	)
}

Nested Route

First, write the sub routing configuration in the routing table

const element = useRoutes([
  {
    path:'/about',
    element:<About/>
  },
  {
    path:'/home',
    element:<Home/>,
    children:[
      {
        path:'news',
        element:<News/>
      },
      {
        path:'message',
        element:<Message/>,
      }
    ]
  }
])

Then use the Outlet tag for display. The principle is the same as that of vue's router view tag:

import React from 'react'
import {NavLink,Outlet} from 'react-router-dom'

export default function Home() {
	return (
		<div>
			<h2>Home Component content</h2>
			<div>
				<ul className="nav nav-tabs">
					<li>
						<NavLink className="list-group-item" to="news">News</NavLink>
					</li>
					<li>
						<NavLink className="list-group-item" to="message">Message</NavLink>
					</li>
				</ul>
				{/* Specifies the location where the routing component is rendered */}
				<Outlet />
			</div>
		</div>
	)
}

Tags: Javascript React

Posted by ljschrenk on Sun, 15 May 2022 01:11:44 +0300