Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Last active March 16, 2018 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.
Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.
withRouteBlock HOC to prevent transitions
export default compose<Props, OwnProps>(
withHistory,
withRouteBlock("Already leaving?")
)(SomeContainer);
import { compose, lifecycle, withState } from 'recompose';
import { History, UnregisterCallback } from 'history';
type Props = {
pristine: boolean;
history: History;
};
type State = {
historyBlock: UnregisterCallback;
};
/**
* HOC that blocks history transition if props.pristine is false
*/
export const withRouteBlock = (message: string) => compose(
lifecycle<Props, State>({
componentDidMount() {
const { history, pristine } = this.props;
if (!history) {
console.warn('history in undefined');
}
if (!pristine) {
this.setState({ historyBlock: history.block(message) })
}
},
componentWillReceiveProps(nextProps) {
const { history, pristine } = nextProps;
const historyBlock = this.state ? this.state.historyBlock : null;
if (!pristine && !historyBlock) {
this.setState({ historyBlock: history.block(message) })
}
else if (historyBlock && pristine) {
historyBlock();
}
},
componentWillUnmount() {
if (this.state && this.state.historyBlock) {
this.state.historyBlock();
}
}
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment