Skip to content

Instantly share code, notes, and snippets.

@lourd
Last active July 11, 2017 14:39
Show Gist options
  • Save lourd/8fc409781667bb25c0e6cd95520ed349 to your computer and use it in GitHub Desktop.
Save lourd/8fc409781667bb25c0e6cd95520ed349 to your computer and use it in GitHub Desktop.
Possible component design & usage for history.before API
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
@withRouter
class BeforeLocationChange extends Component {
static propTypes = {
history: PropTypes.shape({
before: PropTypes.func.isRequired,
}).isRequired,
handler: PropTypes.func.isRequired,
}
componentDidMount() {
this.unsub = this.props.history.before(this.props.handler)
}
componentDidUpdate(prevProps) {
if (this.props.handler !== prevProps.handler) {
this.unsub()
this.unsub = this.props.history.before(this.props.handler)
}
}
componentWillUnmount() {
this.unsub()
}
render() {
return null
}
}
class Foo extends Component {
state = {
value: '',
showLeaveModal: false,
}
checkWhetherToBlock = (location, action) => {
if (!this.state.value) return
return new Promise(resolve => {
this.resolveBlock = resolve
this.setState({ showLeaveModal: true })
})
}
// assuming `choice` is a boolean
onModalDecision = choice => {
this.resolveBlock(choice)
this.setState({ showLeaveModal: false })
}
onChange = (evt) => {
this.setState({ value: evt.target.value })
}
render() {
return (
<div>
<BeforeLocationChange handler={this.checkWhetherToBlock} />
<input onChange={this.onChange} />
{this.state.showLeaveModal
<MyCustomModal
onChoice={this.onModalDecision}
message={this.state.value.length > 200
? "You sure? You've typed a lot"
: "This won't be saved if you leave"
}
/>
}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment