Skip to content

Instantly share code, notes, and snippets.

@Vadorequest
Last active December 5, 2017 19:42
Show Gist options
  • Save Vadorequest/bce4e6ddeec9a89d59d883ccc412d0f1 to your computer and use it in GitHub Desktop.
Save Vadorequest/bce4e6ddeec9a89d59d883ccc412d0f1 to your computer and use it in GitHub Desktop.
HOC component to get the history using React-Router v4 (alpha)
import withRouter from './utils/withRouter';
const MyComponent = ({ history }) =>
<button onClick={() => history.goBack()}>Back</button>
export default compose(
withRouter,
)(MyComponent);
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