kim tech
kim tech

Reputation: 91

How do I go to home page when i refresh a page?

I'm trying to refresh react website and I want to show an alert and if user check confirm the website is going to home page with route whenever refresh my website. so, I tried to use onbeforeunload but it's not what i expected . This is what im using, but when i refresh then it can't go to home page

 useEffect(() => {
    window.onbeforeunload = function () {
      return true;
    };
    return () => {
      window.onbeforeunload = null;
    };
  }, []);
I'd like to know how to go to home page when i refresh a page. Thank you in advance !

Upvotes: 1

Views: 197

Answers (1)

Viet
Viet

Reputation: 12787

You should using addEventListener and removeEventListener to do this:

useEffect(() => {
  const beforeunloadHandle = () => {
    return true;
  };

  window.addEventListener("beforeunload", beforeunloadHandle);
  return () => {
    window.removeEventListener("removeEventListener", beforeunloadHandle);
  };
}, []);

Upvotes: 2

Related Questions