Skip to content

Instantly share code, notes, and snippets.

@BTMPL
Created January 13, 2017 21:01
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/0cd6a526b5a98ea9d0ec0b9482e7380b to your computer and use it in GitHub Desktop.
Save BTMPL/0cd6a526b5a98ea9d0ec0b9482e7380b to your computer and use it in GitHub Desktop.
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link, withRouter} from 'react-router'
import withExampleBasename from '../withExampleBasename'
const App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/dashboard" activeClassName="active">Dashboard</Link></li>
<li><Link to="/form" activeClassName="active">Form</Link></li>
</ul>
{this.props.children}
</div>
)
}
})
class ConfirmNavigation extends React.Component {
componentWillMount() {
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
}
routerWillLeave() {
return 'You have unsaved information, are you sure you want to leave this page?'
}
render() {
return null;
}
}
const PreventFromLeaving = withRouter(ConfirmNavigation);
const Dashboard = React.createClass({
render() {
return <h1>Dashboard</h1>
}
})
const Form = withRouter(
React.createClass({
getInitialState() {
return {
textValue: 'ohai'
}
},
handleChange(event) {
this.setState({
textValue: event.target.value
})
},
handleSubmit(event) {
event.preventDefault()
this.setState({
textValue: ''
}, () => {
this.props.router.push('/')
})
},
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>Click the dashboard link with text in the input.</p>
{<PreventFromLeaving route={this.props.route} />}
<input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} />
<button type="submit">Go</button>
</form>
</div>
)
}
})
)
render((
<Router history={withExampleBasename(browserHistory, __dirname)} routes={
<Route path="/" component={App}>
<Route path="dashboard" component={Dashboard} />
<Route path="form" component={Form} />
</Route>
}>
</Router>
), document.getElementById('example'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment