7

I am having a modal which while opening pushes a hash to url example.com/#modal, on browser back button click, I want to recognise that event so that I can toggle the state of modal. the point is, since Im using it with next.js (server side rendering), I will not be having access to window object (correct me if I am wrong). so I need an alternate way to handle the event of browser back button.

Summy Sumanth
  • 363
  • 2
  • 4
  • 10

3 Answers3

10

To add to Artinium's answer with a pratical example for your case, you can use next/router's beforePopState to act on changes to the session history navigation (back/forward actions), and make sure it'll only happen when leaving the current page.

useEffect(() => {
    router.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            // Will run when leaving the current page; on back/forward actions
            // Add your logic here, like toggling the modal state
        }
        return true;
    });

    return () => {
        router.beforePopState(() => true);
    };
}, [router]); // Add any state variables to dependencies array if needed.
juliomalves
  • 21,997
  • 12
  • 75
  • 81
  • 2
    This is a good solution but you should be comparing `as` (another prop on the callback object) to `router.asPath`, not `url`. The url maybe different even on the same page – nathajamal Nov 02 '21 at 16:35
  • 1
    @nathajamal Yes, that's a good point. Since `asPath` is the path shown in the browser it only makes sense that it should be compared to the `as` prop. I've updated the answer. – juliomalves Nov 02 '21 at 16:57
  • Why does this need to be in a `useEffect` hook? @juliomalves – Sunny Patel Mar 20 '22 at 14:00
  • 3
    @SunnyPatel Because adding a listener to the `beforePopState` event of `next/router` should occur on the client-side. – juliomalves Mar 20 '22 at 14:05
1

in NextJs we can use beforePopState function and do what we want such close modal or show a modal or check the back address and decide what to do

https://stackoverflow.com/a/60702584/4717739

https://stackoverflow.com/a/69560739/4717739

Mohammad Zaer
  • 523
  • 5
  • 8
0

@Summy I hope your issue is resolved by now. If not you can try this for the browser back button:- Next.js + React Go back to the previous page If you want to use hashbang URLs you can't use SSR, since /# and /#/one is the same route server-side, so there is no way for the server to know what to render, it will need to send a basic template and let the client fill it, in that case, I think using CRA or Parcel with React Router and its HashRouter is a better option, that way you will have a single index.html and let the client decide what to render.

anup
  • 525
  • 9
  • 32