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

How to show custom modal box if user click back button in browser.i already have a modal box working w

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 .

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 .

Share Improve this question edited Nov 3, 2017 at 12:48 Valeriy 1,4453 gold badges22 silver badges46 bronze badges asked Nov 3, 2017 at 12:27 Rishabh MishraRishabh Mishra 5088 silver badges21 bronze badges 2
  • Show some code? We can't read your mind... – Rajendran Nadar Commented Nov 3, 2017 at 12:31
  • 1 Check this stackoverflow./questions/32841757/… – Shubham Khatri Commented Nov 3, 2017 at 12:32
Add a ment  | 

2 Answers 2

Reset to default 5
  1. I have a separate ponent in my project for modal box called 'Confirm' which I use in other ponent lets call it 'Sample'.
  2. In my Sample ponent, I maintain a state for managing display of that Confirm box.
  3. 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.

Lets say you have some pages and all of them are wrapped inside Container ponent, try something like this:

class Container extends Component {

state = {
 showModal: false
}

handleBackClick(){
 this.props.history.push(this.props.location.pathname)
 this.setState({showModal: true})
}

ponentDidMount(){
 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744894007a4599585.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信