Rishabh Mishra
Rishabh Mishra

Reputation: 508

How to Show Modal Box on Back button in react-router v4?

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 .

Upvotes: 2

Views: 5157

Answers (2)

Krishna Nigalye
Krishna Nigalye

Reputation: 1076

  1. I have a separate component in my project for modal box called 'Confirm' which I use in other component lets call it 'Sample'.
  2. In my Sample component, I maintain a state for managing display of that Confirm box. enter image description here
  3. To detect browser/device back button, I have added an event in my useEffect function as shown below.

enter image description here

Here is my goBackButtonHandler function.

enter image description here

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();

enter image description here

This triggers the event and I can see Modal box if my fields are dirty. That's it! Hope this will help.

Upvotes: 5

krmzv
krmzv

Reputation: 387

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.

Upvotes: 1

Related Questions