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.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.”


Leave a Reply

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