Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show alert on Browser Back Button event on react js

Tags:

reactjs

I have to show an alert on the browser back event on React js. I have tried using the addEventListener but I'm not sure where to place the code in the React page. Should I place in any life-cycle hooks or in the render? I'm not sure. Please help me out.

like image 273
Ashok R Raghu Avatar asked May 03 '19 09:05

Ashok R Raghu


People also ask

What is the event for browser back button?

The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history. back() in JavaScript), when navigating between two history entries for the same document.


2 Answers

if you use react hooks you can use useEffect hooks to do it in following step

import React, { useState, useEffect } from "react";

const [finishStatus, setfinishStatus] = useState(false);

const onBackButtonEvent = (e) => {
    e.preventDefault();
    if (!finishStatus) {
        if (window.confirm("Do you want to go back ?")) {
            setfinishStatus(true)
            // your logic
            props.history.push("/");
        } else {
            window.history.pushState(null, null, window.location.pathname);
            setfinishStatus(false)
        }
    }
}

  useEffect(() => {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', onBackButtonEvent);
    return () => {
      window.removeEventListener('popstate', onBackButtonEvent);  
    };
  }, []);
like image 107
Lahardi Alkawero Avatar answered Oct 30 '22 21:10

Lahardi Alkawero


I found this solution and it is working fine for me.

constructor(props) {
    super(props);
    this.state = {
        onClickBackButton: false
    };
}
componentDidMount() {
   window.history.pushState(null, null, window.location.pathname);
   window.addEventListener('popstate', this.onClickBackButton);
}

onBackButtonEvent = (e) => {
    e.preventDefault();
    if (!this.onClickBackButton) {

        if (window.confirm("Do you want to go back without submitting details?")) {
            this.onClickBackButton= true;
            // your custom logic to page transition,like react-router-dom 
            history.push()
        } else {
            window.history.pushState(null, null, window.location.pathname);
            this.onClickBackButton= false;
        }
    }
}

componentWillUnmount = () => {
    window.removeEventListener('popstate', this.onClickBackButton);
}

Ref

like image 41
Atit More Avatar answered Oct 30 '22 22:10

Atit More