Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save hungdev/710dae289d4a2cf7f1e679d87b9eb986 to your computer and use it in GitHub Desktop.

Select an option

Save hungdev/710dae289d4a2cf7f1e679d87b9eb986 to your computer and use it in GitHub Desktop.
Listen to page refresh and window close on react-router.md

https://stackblitz.com/edit/listen-to-page-refresh-and-window-close-on-react-router?file=index.js

https://stackoverflow.com/questions/49363412/listen-to-page-refresh-and-window-close-on-react-router

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { withRouter, Prompt } from 'react-router';

class PreventRouteChange extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentWillMount() {
    onbeforeunload = e => "Don't leave"
  }

  componentWillUnmount() {
    onbeforeunload = null
  }

//   componentDidUpdate = () => {
//   if (shouldBlockNavigation) {
//     window.onbeforeunload = () => true
//   } else {
//     window.onbeforeunload = undefined
//   }
// }

  render() {
    return (
      <div>
      <Prompt when={true} message={"Cancel me"}/>
      <div>
      aaaaa
      </div>
        
      </div>
    );
  }
}


export default withRouter(PreventRouteChange);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment