React router v6 changes
Install the latest version of React v17 and react-router-dom v6
npm install react-router-dom@latest
Or yarn add react-router-dom@latest
- No <Switch> anymore. Nested routes
import <Routes> from ‘react-router-dom’ and around the <Route>
<Routes>
<Route.../>
<Route.../>
</Routes>
All Route in the hug of mommy <Routes>, no other tags
2. component to element
<Route path='/' element='<HomePage/>' />
the page is no longer in {…}
3.no exact
don’t need to add ‘exact’ to the Route to direct the page
<Route exact path='/' element='<Page/>' />
delete the exact kind of transfer to index
an index route at any level of the route hierarchy that will render when the parent matches but none of its other children do.
<Route index element={<Home />} />
4.Use :style
syntax in your route path and useParams()
<Routes>
<Route
path="invoices/:invoiceId"
element={<Invoice />}
/>
</Routes>
<Route path='/*' />
*means all
5. Route components no longer have route props(history, location, and match). Create your own hooks with withRouter and useParams(still work).
RRDv6 doesn’t export a withRouter
HOC so you have to roll your own if you need one for "legacy" components still receiving route props
const withRouter = WrappedComponent => props => {
const params = useParams();
// etc... other react-router-dom v6 hooks
return (
<WrappedComponent
{...props}
params={params}
// etc...
/>
);
};
export default withRouter(Post);
the params will lead to props
6.no Redirect,change to Navigate
<Navigate to='/home' />
7.<Link> too change URL or {useNavigate}
import {useNavigate} from 'react-router-dom'
const navigate=useNavigate()
...
navigate('/home')
navigate(-1)
navigate(-2)
navigate to direct page, -1 means go back, -2 means back back. lol