'How can i handle page refresh event in React.js

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave.

but issue is that when user refresh page using browser refresh btn in google chrome that time below error occur

enter image description here

I tired this code but doesn't work in react.js please help

  window.hideWarning = false;
    window.addEventListener('beforeunload', (event) => {
      if (!window.hideWarning) {
        event.preventDefault();
        event.returnValue = '';
      }
    });

Also try this code

window.onbeforeunload = function () { return ''; }.bind(this);


Solution 1:[1]

you can also use that

winodow.location.reload(true) winodow.location.reload(false)

Solution 2:[2]

Please use this:

console.log(window.performance.navigation)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Darshan Dhameliya
Solution 2 Ihor Konovalenko