Skip to content

Instantly share code, notes, and snippets.

@cjies
Last active June 19, 2017 13:20
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 cjies/94aead6b0d59e906fa08836182958763 to your computer and use it in GitHub Desktop.
Save cjies/94aead6b0d59e906fa08836182958763 to your computer and use it in GitHub Desktop.
Custom dialog with react-router v4
// -------------------------------------
// Example from react-router
// @ref https://reacttraining.com/react-router/web/example/preventing-transitions
// -------------------------------------
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Form from './Form';
import getUserConfirmation from './get_user_confirmation';
const CustomDialogExample = () => (
<Router getUserConfirmation={getUserConfirmation}>
<div>
<ul>
<li><Link to="/">Form</Link></li>
<li><Link to="/one">One</Link></li>
<li><Link to="/two">Two</Link></li>
</ul>
<Route path="/" exact component={Form}/>
<Route path="/one" render={() => <h3>One</h3>}/>
<Route path="/two" render={() => <h3>Two</h3>}/>
</div>
</Router>
);
export default CustomDialogExample;
import React, { PureComponent } from 'react';
import { Prompt } from 'react-router-dom';
class Form extends PureComponent {
state = {
isBlocking: false
}
render() {
const { isBlocking } = this.state;
return (
<form
onSubmit={event => {
event.preventDefault();
event.target.reset();
this.setState({
isBlocking: false
});
}}
>
<Prompt
when={isBlocking}
message={location => (
`Are you sure you want to go to ${location.pathname}`
)}
/>
<p>
Blocking? {isBlocking ? 'Yes, click a link or the back button' : 'Nope'}
</p>
<p>
<input
size="50"
placeholder="type something to block transitions"
onChange={event => {
this.setState({
isBlocking: event.target.value.length > 0
})
}}
/>
</p>
<p>
<button>Submit to stop blocking</button>
</p>
</form>
);
}
}
export default Form;
import React from 'react';
import { unmountComponentAtNode, render } from 'react-dom';
// Try to use your component
import ConfirmPopup from 'GET_UR_OWN_COMP/ConfirmPopup';
/**
* Custom confirm dialog with <ConfirmPopup>
*
* @param {String} message
* @param {Function} callback
*/
function getUserConfirmation(message, callback) {
// Create a temporary modal DOM element
const modal = document.createElement('div');
document.body.appendChild(modal);
const allowTransition = (answer) => () => {
// Unmount and remove modal DOM
unmountComponentAtNode(modal);
document.body.removeChild(modal);
callback(answer);
};
const confirmPopup = (
<ConfirmPopup
message={message}
onConfirm={allowTransition(true)}
onClose={allowTransition(false)} />
);
render(confirmPopup, modal);
}
export default getUserConfirmation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment