React ~ Router ~ Preventing Transitions - rohit120582sharma/Documentation GitHub Wiki

Sometimes you want to prevent the user from navigating away from a page. The most common use case is when they have entered some data into a form but haven't submitted it yet, and you don't want them to lose it.

import { Prompt } from "react-router-dom";

export default function PreventingTransitionsExample() {
    return (
        <Router>
            <ul>
                <li><Link to="/">Form</Link></li>
                <li><Link to="/one">One</Link></li>
            </ul>

            <Switch>
                <Route path="/" exact children={<BlockingForm />} />
                <Route path="/one" children={<h3>One</h3>} />
            </Switch>
        </Router>
    );
}

function BlockingForm() {
    let [isBlocking, setIsBlocking] = useState(false);

    return (
    <form
        onSubmit={(event) => {
            event.preventDefault();
            event.target.reset();
            setIsBlocking(false);
        }}>
        <Prompt
            when={isBlocking}
            message={
                (location) => `Are you sure you want to go to ${location.pathname}`
            } />

        <div>
        <input
                size="50"
                placeholder="type something to block transitions"
                onChange={event => {
                    setIsBlocking(event.target.value.length > 0);
                }} />
            <button>Submit to stop blocking</button>
        </div>
    </form>
    );
}
⚠️ **GitHub.com Fallback** ⚠️