Skip to content

Instantly share code, notes, and snippets.

@gotnospirit
Created Jul 28, 2017
Embed
What would you like to do?
React Router v4 + React Transition Group v2
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'))
@gotnospirit
Copy link
Author

gotnospirit commented Jul 28, 2017

React v15.5.3
React Router v4.1.2
React Transition Group v2.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment