Reputation: 101
I have built a PWA mobile application on React. The app is multi-page, with a flow like this: Home -> Search Results -> Details -> Checkout. Here the routing is being handeled by NextJS.
Now on each page, there are several bottomsheets and subpages being opened on the click of some buttons/icons. This is being handeled by overlaying a sheet on top of the existing page and no URL change is involved. A back/cross icon has been provided on all these subpages/bottomsheets to close them and navigate back to the main page.
Now, I am facing a user experience issue, where most of the users are hitting the back button on their device to try to navigate back from the subpage/close the bottomsheet. This is equivalent to hitting the back button on the browser which is causing the URL to change and the app navigating to the previous page instead to closing the subpage/bottomsheet as expected.
How can I handle this?
I looked into the popstate event handler, but that will not stop the broswer from navigating back.z
Update:
I have done something like this ->
const openBottomsheet = () => {
window.location.hash = "bottomsheet";
//code to handle mounting the bottomsheet on DOM.
}
useEffect(() => {
addEventListener('popstate', (event) => globalDispatcher(hideBottomSheet()) );
return () => {
removeEventListener('popstate',(event) => globalDispatcher(hideBottomSheet()));
}
})
This code is adding a #bottomsheet to the end of the url when the bottomsheet is being opened, and on clicking back it is removing the hash, hence it is staying on the same page, and closing the bottomsheet.
However, on removing the #bottomsheet from the URL, it is reloading the page which is not desired. How can I fix that?
Update 2:
I tried the history.pushState method, it is working as expected. Thank you.
Update 3:
The history.pushState method is working unpredictably. On first time page load, it is causing page reload on pressing back button to close overlay. But if I reload the page once, then it starts working fine.
Upvotes: 0
Views: 1144
Reputation: 611
You should use the history API.
The history.pushState()
function adds a state to the history stack. So when you press the back button, you go back to this previous state.
The idea here is to add a new state everytime you open a sheet. And to close you sheets in the changing state event handler.
Here is an exemple :
// The changing state event handler
window.onpopstate = (event) => {
// Do close the last sheet
}
// A generic function you call everytime a sheet is open
function onNewSheet() {
history.pushState({sheet: 'open'}, "", "")
}
Therefore if you do something like that, you own back icon could just trigger the history.back()
function.
Also, if needed you can store information in the state (here I've only put a dummy {sheet: 'open'}
) that can be retreived with history.state
.
Upvotes: 0