For the use case when a page has an internal route, the prompt triggers even when navigating to an internal route where a prompt might not be necessary, see code example. Is there a way to disable the prompt when navigating to known safe routes?
import React, {Component} from 'react';
import {BrowserRouter, Route, Switch, Link, Prompt} from 'react-router-dom';
export default class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route component={About} path={"/about"}/>
<Route component={Home} path={"/"}/>
</Switch>
</BrowserRouter>
);
}
}
class Home extends Component {
constructor(props) {
super(props);
this.state = {input: 'hello?'}
}
render() {
return (
<div>
<h1>Home</h1>
<input value={this.state.input}
onChange={(e) => this.setState({input: e.target.value})}/><br />
<Link to={"/info"}>More Info</Link><br />
<Link to={"/about"}>About Page</Link><br />
{/*Triggers even when going to /info which is unnecessary*/}
<Prompt message="Move away?" when={this.state.input !== 'hello?'}/>
<Route path={"/info"} component={Info}/>
</div>
);
}
}
class About extends Component {
render() {
return (
<h1>About page</h1>
);
}
}
class Info extends Component {
render() {
return (
<p>Here be some more info</p>
);
}
}
In the example above, About is a different page and so should trigger when the input has changed, which it does correctly. But the /info route is an internal route for Home, so the prompt is unnecessary, the internal state of Home is preserved after navigation so nothing is lost.
The actual use case here is for a modal to be shown when the route is active, but that is mostly CSS stuff so I excluded it from the example.