Reputation: 1669
With Expo Router, there are several ways to detect navigation changes (usePathname
, state
from Navigator
, etc.).
For certain use cases it would be helpful to also be able to check if the navigation action was triggered by the user going back one ore more screens using the browser history.
Here is one such example, where we scroll to the top on each screen, but would want to omit that when the user navigates back one or more pages, so that the browsers scroll position doesn't get lost.
import { Navigator } from 'expo-router'
export default function AppLayout() {
const { state } = Navigator.useContext()
// Todo: Don't scroll to top on history.back()
useEffect(() => {
if (typeof window !== 'undefined' && window.scrollTo) {
window.scrollTo(0, 0)
}
}, [state])
return (
<TabLayout>
<ResponsiveNavigator />
</TabLayout>
)
}
I've already tried several brute approaches unsuccessfully, like comparing current and prev pathnames (usePathname()
also gets updated on history.back()
) as well as using window.addEventListener('popstate', …)
(hacky/unreliable).
So I'm curious if I'm missing something here and this is possible with Expo Routers API in a straight forward way.
Upvotes: 1
Views: 716