Created
September 22, 2016 19:53
-
-
Save nickydonna/3d76397a92551f449637590bf0413133 to your computer and use it in GitHub Desktop.
A Contoller ReactRouter for v4
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
/* @flow */ | |
import BrowserHistory from 'react-history/BrowserHistory' | |
import {Push, Replace} from 'react-history' | |
import React, {Component} from 'react' | |
import {StaticRouter} from 'react-router' | |
type RouterProps = { | |
onChange: (action: string, location: Object) => void, | |
pathname: string, | |
navigation?: 'PUSH' | 'REPLACE', | |
}; | |
/** | |
* A router that exposes ways to connect to store such as Redux | |
*/ | |
class ControlledRouter extends Component { | |
props: RouterProps | |
static defaultProps: { | |
navigation: string | |
} | |
render() { | |
const { navigation, pathname, onChange } = this.props | |
return ( | |
<BrowserHistory key={pathname} > // github.com/yahoo/react-intl/issues/234#issuecomment-163366518 | |
{({ history, action, location }) => { | |
const pathnameChanged = location.pathname !== pathname | |
if (pathnameChanged) { | |
setImmediate(() => onChange(action, location)) | |
} | |
return ( | |
<StaticRouter | |
action={action} | |
location={location} | |
onPush={history.push} | |
onReplace={history.replace} | |
blockTransitions={history.block} | |
> | |
{pathnameChanged && navigation === 'PUSH' && | |
<Push path={pathname}/> | |
} | |
{pathnameChanged && navigation === 'REPLACE' && | |
<Replace path={pathname}/> | |
} | |
</StaticRouter> | |
) | |
} } | |
</BrowserHistory> | |
) | |
} | |
} | |
ControlledRouter.defaultProps = { | |
navigation: 'PUSH' | |
} | |
export default ControlledRouter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The BACK, FORWARD and POP actions need internal state to avoid infinite history changes