Answer the question
In order to leave comments, you need to log in
How to listen to browser back button and trigger actions (React + Next.js )?
I use React in conjunction with Next.js. There is a stepper, it is independent of the url, but depends on the store in the editor.
Now I am doing the functionality on the back button and the client wants it to be the same on both the custom button and the browser button.
The stepper is permanently on the /new
url.
I try to catch the desired action with the help of package history :
import Router from 'next/router';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
history.listen((location) => {
if (location.action === 'POP') {
dispatch(updateScreenStep('back'));
Router.push('/new'); // всегда обновляю урлу, что-бы не пошло дальше неё
}
});
Answer the question
In order to leave comments, you need to log in
maybe it will come out stupidly in _app.js or put a popstate event handler in some main Layout.js wrapper?
React.useEffect(() => {
window.addEventListener('popstate', doStuff)
return () => {
window.removeEventListener('popstate', doStuff)
}
}, [doStuff]) // function doStuff() {}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question