ReactJs Browser Button Back

I use Reactjs.I want to warn the user when he clicks the back button. What I had was

handleWindowClose = (ev) => {
  ev.preventDefault();
  return ev.returnValue = 'Leaving this page will loose data';
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
}

componentWillUnmount = () => {
    window.removeEventListener('beforeunload',this.handleWindowClose);
}

However, this does not work with the back button. So I tried to do it

handleWindowClose = (ev) => {
        ev.preventDefault();
        return ev.returnValue = 'Leaving this page will loose data';        
}

onBackButtonEvent = (e) => {
    e.preventDefault();
    if(confirm("Do you want to loose this data")){
    window.history.go(0);
    }else {
    window.history.forward();
  }
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
    window.addEventListener('popstate',this.onBackButtonEvent);
}

componentWillUnmount = () => {
    window.removeEventListener('beforeunload',this.handleWindowClose);
    window.removeEventListener('popstate',this.onBackButtonEvent);
}

I do not use response-router.Is there is a better way to do this using only react. I also want the window to remain on this page without using history.forward (), since I will lose the state of the window.

+4
source share
1 answer

EDIT

It seems like onbeforeunloadthis is what you want: check out this related question , which contains a useful demo .

MDN .


, react-router, javascript

, . URL, onhashchange.

:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;

react-router go, , React. browserHistory .

+1

All Articles