Created
July 28, 2017 12:22
-
-
Save gotnospirit/24e9becc073caf033b3a436b959626b7 to your computer and use it in GitHub Desktop.
React Router v4 + React Transition Group v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { render } from 'react-dom' | |
import { BrowserRouter, Route, Link } from 'react-router-dom' | |
import { TransitionGroup, Transition } from 'react-transition-group' | |
import matchPath from 'react-router-dom/matchPath' | |
const routes = [{ | |
key : 'home', | |
path : '/', | |
content : 'Homepage', | |
exact : true | |
}, { | |
key : 'about', | |
path : '/about', | |
content : 'This is all about', | |
exact : true | |
}] | |
const filterRoutes = (location) => { | |
return routes.filter(({ path, strict, exact }) => { | |
return !!matchPath(location.pathname, { | |
path, | |
strict, | |
exact | |
}) | |
}) | |
} | |
const App = () => ( | |
<div> | |
<div style={{ border : '1px solid black', padding : '.2em' }}> | |
{routes.map(({ path, key }) => ( | |
<Link key={'link-' + key} to={path} style={{ margin : '0 1em'}}>{key}</Link> | |
))} | |
</div> | |
<Route render={({ location }) => ( | |
<TransitionGroup appear={true}> | |
{filterRoutes(location).map(({ key, content, ...props }) => ( | |
<Transition | |
key={'child-' + key} | |
timeout={0} | |
onEnter={() => { console.log(key + ' enter') }} | |
onEntering={() => { console.log(key + ' entering') }} | |
onEntered={() => { console.log(key + ' entered') }} | |
onExit={() => { console.log(key + ' exit') }} | |
onExiting={() => { console.log(key + ' exiting') }} | |
onExited={() => { console.log(key + ' exited') }}> | |
<Route | |
{...props} | |
location={location} | |
render={() => ( | |
<div>{content}</div> | |
)} /> | |
</Transition> | |
))} | |
</TransitionGroup> | |
)}/> | |
</div> | |
) | |
render(<BrowserRouter> | |
<App /> | |
</BrowserRouter>, document.getElementById('root')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
React v15.5.3
React Router v4.1.2
React Transition Group v2.2.0