Malvina Georgiana
Malvina Georgiana

Reputation: 11

How can you show a modal in react when you press the back button browser?

I need to show a modal when user wants to leave a specified page. When User wants to go on a different link from the page, I solve this with getUserConfirmation like that:

const getUserConfirmation = (message, callback) => {
const history = createBrowserHistory({
     forceRefresh: true
     })

 if (history.location.pathname == "/add/car") {
     store.dispatch(showModal('ConfirmationLeavingAddPageModal', { callback }));
 }
 }

The problem is when I press the back button on browser it doesn't work anymore. Any Help Accepted?

Upvotes: 1

Views: 384

Answers (1)

MaddEye
MaddEye

Reputation: 741

For react-router 2.4.0+

componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
        if (history.location.pathname == "/add/car") {
            store.dispatch(showModal('ConfirmationLeavingAddPageModal', {
                callback
            }));
        }
    })
}

in addition you need to import { withRouter } from 'react-router' and export default withRouter(YourComponent)

Upvotes: 1

Related Questions