Last active
December 5, 2017 19:42
-
-
Save Vadorequest/bce4e6ddeec9a89d59d883ccc412d0f1 to your computer and use it in GitHub Desktop.
HOC component to get the history using React-Router v4 (alpha)
This file contains hidden or 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 withRouter from './utils/withRouter'; | |
const MyComponent = ({ history }) => | |
<button onClick={() => history.goBack()}>Back</button> | |
export default compose( | |
withRouter, | |
)(MyComponent); |
This file contains hidden or 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 wrapDisplayName from 'recompose/wrapDisplayName'; | |
import hoistStatics from 'recompose/hoistStatics'; | |
import { propTypes } from 'react-router'; | |
import { Subscriber } from 'react-broadcast'; | |
const withRouter = (options) => { | |
const hoc = hoistStatics((WrappedComponent) => { | |
const WithRouter = (props, { router, history }) => { | |
const modifiedHistory = { ...history }; | |
delete modifiedHistory.location; | |
const componentProps = { | |
...props, | |
history: modifiedHistory, | |
router, | |
}; | |
return ( | |
<Subscriber {...props} channel="location"> | |
{locationContext => ( | |
<WrappedComponent | |
{...componentProps} | |
location={locationContext} | |
/> | |
)} | |
</Subscriber> | |
); | |
}; | |
WithRouter.contextTypes = { | |
history: React.PropTypes.object, | |
router: propTypes.routerContext, | |
}; | |
WithRouter.displayName = wrapDisplayName(WrappedComponent, 'withRouter'); | |
WithRouter.WrappedComponent = WrappedComponent; | |
return WithRouter; | |
}); | |
if (typeof options === 'function') { | |
return hoc(options); | |
} | |
return hoc; | |
}; | |
export default withRouter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment