T
TanStack3y ago
foreign-sapphire

Close a modal using the back key, with tanstack-router

I have an app where modals are NOT controlled by url query params. I would like however to be able to close them using the back browser button (for mobile users basically) In the render function of my modal component, I was considered adding:
const location = useLocation() // I'm currently on @tanstack/react-location, but I can migrate to tanstack-router if this solves my issue.

const handleBack = useCallback((e: PopStateEvent) => {
location.history.forward() // back + forward = we stay on the same page
close() // this closes the modal
}, [])

useEffect(() => {
window.addEventListener("popstate", handleBack)
return () => {
window.removeEventListener("popstate", handleBack)
}
}, [])
const location = useLocation() // I'm currently on @tanstack/react-location, but I can migrate to tanstack-router if this solves my issue.

const handleBack = useCallback((e: PopStateEvent) => {
location.history.forward() // back + forward = we stay on the same page
close() // this closes the modal
}, [])

useEffect(() => {
window.addEventListener("popstate", handleBack)
return () => {
window.removeEventListener("popstate", handleBack)
}
}, [])
Well it works. The modal is closed when I press the back button. But at the same time I see the previous page flashing before coming back to the current one. Is there any way to block tanstack-router navigation in such a case? By the way, what's your opinion about modals? Should I use query-params to open them? What are the pro & cons, beyond the back navigation key?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?