react-router-alive
A keep-alive route component for react-router.
Why you need it
You may don't want to unmount a route component when switching to another one.
How it works
A AliveRoute
component is provided to work within react-router, every target component of AliveRoute
will be wrapped in a div
element respectively, which means your dom structure will be changed if you use this repository, and react-native is not supported for the moment.
Despite the route being matched or not, all target components will be mounted, of which the css attribute display
of all wrapper div
s are set to none
except the matched route.
For now the package only support "react": ">=16.8.4"
and "react-router": ">=5.0.0"
.
The idea of setting style={{display: 'none'}}
to realise this is from here.
How to use
children
(wrapped JSX elements) and render
attribute are not supported in AliveRoute
, in which it is recommended to use component
attribute to set a target route component, other basic usage of AliveRoute
is almost the same with Route
in react-router, here is the docs.
For customization reasons, you can use property activeClass
to set css class for the matched route component and disactiveClass
to set css class for the others.
A demo project is provided above or you can follow the steps below.
yarn add react-router-alive
import Router Link from 'react-router-dom';import AliveRoute from 'react-router-alive'; import Foo from './Foo';import Bar from './Bar'; // ... <div ="app"> <Router> <div> <ul> <li> <Link ="/foo">Foo</Link> </li> <li> <Link ="/bar">Bar</Link> </li> <li /> </ul> <AliveRoute ="/foo" = ="active" ="disactive" /> <AliveRoute ="/bar" = ="active" ="disactive" /> </div> </Router> </div>;