-1

I do not want a user to click browser back button and forward button from my page because my page loads stored sessions every time. If user is clicking on these buttons then i simply want him to navigate to the homepage.

For security purpose, sessions are being maintained by the backend APIs so if user will fluctuate on browser's forward and back buttons then it will cause session disruption.

I have searched everywhere and tried lots of things but no solution is compatible with the v6 of react-router-dom. There must be solution for this. Please help me out in getting the same.

Anshul
  • 51
  • 1
  • 10
  • 2
    does this answer your question ? https://stackoverflow.com/questions/71369320/how-to-controling-browser-back-button-with-react-router-dom-v6, – Alpha Sep 06 '22 at 05:55
  • No it doesn't help out in any way. – Anshul Sep 06 '22 at 06:02
  • I just don't want that user is able to click on browser forward and back button and if he does so, then i will simply just forward him to the homepage. – Anshul Sep 07 '22 at 05:15

1 Answers1

3

this was my question recently. I searched a lot but have nothing found to do this work with react-router v6. but you can handle browser back and forward buttons using window 'popstate' event. I wrote a hook for connecting, detect and handle this event(useBackButton):

import { useEffect, useState } from "react";

const useBackButton = (callback) => {
  const [isBack, setIsBack] = useState(false);

  const handleEvent = () => {
    setIsBack(true);
    callback();
    window.history.go(1);
  };

  useEffect(() => {
    window.addEventListener("popstate", handleEvent);
    return () => window.removeEventListener("popstate", handleEvent);
  });

  return isBack;
};

export default useBackButton;
you can write your function that does your desired work and send it to this hook. then call this hook in every component that you want.
  • Thanks for your solution. However, when i tried to do so, i don't follow how can i call and render this hook on browser back event to every component. Can you please guide me? or please share any demo code or codesandbox link so that i can get a better idea. – Anshul Sep 07 '22 at 05:13
  • 1
    Yes of course. you can see this codesandbox link: https://codesandbox.io/s/proud-dream-3tn2hg?file=/src/hooks/useBackButton.js use this custom hook in a page component that you want to handle back (or forward) button. for example i used this hook in my About page. in this page, if you click on back button, you will navigate to Contact page. if you want to navigate to 'home' page, replace '/contact' route in params of navigate() function in callback to your desired route(e.g. '/' or '/home' etc). – Ali.Moghimi Sep 09 '22 at 15:45
  • 1
    Good solution, what about browser forward button click? – James Oct 02 '22 at 08:14