Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to have an event handler for the browser's back button with next.js

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.

like image 790
Summy Sumanth Avatar asked Oct 16 '22 03:10

Summy Sumanth


People also ask

What is the event for browser back button?

Normally, the onbeforeunload event is used for handling browser back button functionality as follows: <body onbeforeunload="HandleBackFunctionality()">

How do I get the browser back button event in JQuery?

You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert("pop"); });


3 Answers

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.
like image 168
juliomalves Avatar answered Nov 12 '22 20:11

juliomalves


@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.

like image 23
anup Avatar answered Nov 12 '22 18:11

anup


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

like image 43
Mohammad Zaer Avatar answered Nov 12 '22 18:11

Mohammad Zaer