Skip to content

Instantly share code, notes, and snippets.

@BTMPL
Created January 13, 2017 21:22
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 BTMPL/67931ce0282bf908759dbc74b5825be3 to your computer and use it in GitHub Desktop.
Save BTMPL/67931ce0282bf908759dbc74b5825be3 to your computer and use it in GitHub Desktop.
import React from 'react'
import { render } from 'react-dom'
import { hashHistory, Router, Route, Link, withRouter} from 'react-router'
const App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/screen1" activeClassName="active">screen 1</Link></li>
<li><Link to="/screen2" activeClassName="active">screen 2</Link></li>
</ul>
{this.props.children}
</div>
)
}
})
class Screen1 extends React.Component {
constructor(...props) {
super(...props);
this.state = {text: ""}
}
render() {
return (
<div>
<PreventFromLeaving route={this.props.route} preventLeaveCallback={() => this.state.text === "screen1"} />
This is screen 1. It will ask you to confirm navigation if the field bellow has text "screen1" in it:
<input type="text" value={this.state.text} onChange={(event) => this.setState({text: event.target.value})}/>
</div>
)
}
}
class Screen2 extends React.Component {
constructor(...props) {
super(...props);
this.state = {text: ""}
}
render() {
return (
<div>
<PreventFromLeaving route={this.props.route} preventLeaveCallback={() => this.state.text === "screen2"} />
This is screen 2. It will ask you to confirm navigation if the field bellow has text "screen2" in it:
<input type="text" value={this.state.text} onChange={(event) => this.setState({text: event.target.value})}/>
</div>
)
}
}
class ConfirmNavigation extends React.Component {
constructor(...props) {
super(...props);
this.routerWillLeave = this.routerWillLeave.bind(this);
}
componentWillMount() {
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
}
routerWillLeave() {
if(this.props.preventLeaveCallback()) return 'You have unsaved information, are you sure you want to leave this page?'
}
render() {
return null;
}
}
const PreventFromLeaving = withRouter(ConfirmNavigation);
render((
<Router history={hashHistory} routes={
<Route path="/" component={App}>
<Route path="screen1" component={Screen1} />
<Route path="screen2" component={Screen2} />
</Route>
}>
</Router>
), document.getElementById('example'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment