JavaScript, ReactJS

React: How To Prompt User of Unsaved Data before Leaving Site

There’s a specific function for this: beforeunload.

Chrome Prompt

Adapt beforeunload to React, we get:

class Prompt extends React.Component {
  componentDidMount() {
    window.addEventListener('beforeunload', this.beforeunload.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.beforeunload.bind(this));
  }

  beforeunload(e) {
    if (this.props.dataUnsaved) {
      e.preventDefault();
      e.returnValue = true;
    }
  }

  render() {...}
}

Also, the thing to keep in mind is that it is not possible to customize the content of the message, due to security reasons. So different browsers will display a pre-designed sentence, e.g.,

  • Firefox displays the string, “This page is asking you to confirm that you want to leave – data you have entered may not be saved.”
  • Chrome displays the string, “Do you want to leave this site? Changes you made may not be saved.”

Standard

2 thoughts on “React: How To Prompt User of Unsaved Data before Leaving Site

  1. peterdedonder says:

    If you write the beforeunload method like this:

    beforeunload = (e) => {
    if (this.props.dataUnsaved) {
    e.preventDefault();
    e.returnValue = true;
    }
    };

    you can write

    window.addEventListener(‘beforeunload’, this.beforeunload);
    and
    window.removeEventListener(‘beforeunload’, this.beforeunload);

  2. Pingback: Jak powiadomić użytkownika o niezapisanych zmianach? - Ach te Internety

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.