How to show custom modal box if user click back button in browser.
i already have a modal box working with field changing and i dont want to use Prompt's window.confirm
.
Asked
Active
Viewed 4,455 times
2

Valeriy
- 1,365
- 3
- 18
- 45

Rishabh Mishra
- 498
- 8
- 21
-
Show some code? We can't read your mind... – Rajendran Nadar Nov 03 '17 at 12:31
-
1Check this https://stackoverflow.com/questions/32841757/detecting-user-leaving-page/45869459#45869459 – Shubham Khatri Nov 03 '17 at 12:32
2 Answers
5
- I have a separate component in my project for modal box called 'Confirm' which I use in other component lets call it 'Sample'.
- In my Sample component, I maintain a state for managing display of that Confirm box.
- To detect browser/device back button, I have added an event in my useEffect function as shown below.
Here is my goBackButtonHandler function.
This function checks if any form input fields are dirty. If yes, I display the Confirm box or I simply go back to previous page. I think you can use similar logic for your code.
In my app, I have back and cancel buttons so for in-app navigation and for browser/device navigation, I simply make React History API call for
history.goBack();
This triggers the event and I can see Modal box if my fields are dirty. That's it! Hope this will help.

knigalye
- 956
- 1
- 13
- 19
1
Lets say you have some pages and all of them are wrapped inside Container component, try something like this:
class Container extends Component {
state = {
showModal: false
}
handleBackClick(){
this.props.history.push(this.props.location.pathname)
this.setState({showModal: true})
}
componentDidMount(){
window.onpopstate = this.handleBackClick.bind(this)
}
render(){
return(
<YourModal isOpen={this.state.showModal} ... />
)
}
}
export default withRouter(Container)
You have to wrap Container with withRouter function in order to have access to route props.

krmzv
- 387
- 3
- 14
-
handleBackClick is listening the event but preventDefault is not working. – Rishabh Mishra Nov 03 '17 at 13:05
-
Sorry, you can safely remove preventDefault. And bind handleBackClick (edited) – krmzv Nov 03 '17 at 13:11
-
But the page will navigate. I want to block the navigation until user confirm in the modal box – Rishabh Mishra Nov 03 '17 at 13:13
-
1Got it, then you have to modify handleBackClick function. You cannot prevent navigating with browser's back button, instead you have to handle redirect in handleBackButton function and take user to the given page again and show modal. – krmzv Nov 03 '17 at 13:28