Home > database >  React onbeforeunload - not sure how to use
React onbeforeunload - not sure how to use

Time:08-13

If a state variable called someVar is true, then when user leaves page (refresh, back, [x] button on window/tab), they get a message. On the message, if they select Cancel, they stay on page. If they leave page, call a function (in this example, call doSomething()).

Note: I would like to use a class component, not functional component.

I have some code here with some parts being pseudocode. I also have a CodeSandbox that is identical to what you see below.

import React from 'react';
import {Button} from 'react-bootstrap';

class Sample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      someVar: false
    }
  }

  componentDidMount() {
    window.addEventListener("beforeunload", this.handleUnload);
    return () => {
      window.removeEventListener("beforeunload", this.handleUnload);
    }
  }

  handleUnload = (e) => {
    e.preventDefault();
    if(this.state.someVar) {
        // then show custom modal
    } else {
        // don't show custom modal
    }
  }

  handleAlert = () => {
    if(yes) {
       doSomething();
    }
    if(no) {
       // nothing. stay on page
    }

  doSomething = () => {
      //call some functions
  }

  render() {
    return (
      <h2 onClick={() => { this.setState({ someVar: true }) }} >
        ClickMe
      </h2>
   );
  }
}

CodePudding user response:

You don't need to use onbeforeunload. IMO it's enough to use componentWillUnmount life cycle as you're already using Class component.

import React from 'react';
import {Button} from 'react-bootstrap';

class Sample extends React.Component {
  // fix this life cycle
  componentWillUnmount() {
    this.handleUnload();
  }

  handleUnload = (e) => {
    e.preventDefault();
    if(this.state.someVar) {
        // then show custom modal
    } else {
        // don't show custom modal
    }
  }
  // the rest of the code ....
}

CodePudding user response:

You can solve it this way as well.

  componentDidMount() {
    window.addEventListener('beforeunload', this.unload);
  }

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

Just what not to use HOC :-)

  • Related