Expo Router - when using router.push() to a screen in a different tab, unable to return to root of push

2k views Asked by At

Scenario:

  • A component that navigates to a specific route
  • This component is used in multiple screens
  • The component is used on screens that are not in the stack of the tab it is pushing the route to
const Component = () => {
  ...
  return (
    <Pressable
       ...
       onPress={() => router.push('[otherTab]/[screenWithinOtherTabStack]')}
    >
    ...
}
  • Once navigated to new screen, a back button is available in the header
...OtherTabNavigator()

 return(
    <Stack
      ...
      screenOptions={{
        ...
        headerLeft={() => (
          <Pressable
            onPress={() => router.back()}
            ...
          >
            ...
  • router.back() will navigate to the [otherTab] rather than the tab/screen it originated from

The pushed route seems to lose any state on routing.

I tried getting the key from the current path with useNavigation() and then navigating to '[otherTab]/[screenWithinOtherTabStack]' passing the key as a param, but I was unable to use the key to navigate back to the specific screens route that the push originated from.

If anyone has any insight to situation like this that have successfully handled, it would be greatly appreciated.

1

There are 1 answers

0
agutierrez On

Each navigator keeps its own navigation history Nesting Navigators so what I did was to centralize the shared navigation logic in the outer navigator. This way, you can easily navigate to the desired screen from any tab.

Example:

Let's say you have a screen like (tabs)/post/[edit].tsx that you want to access from other tabs. Instead, move it up in your project structure. Now, you can navigate to this screen using a unified route like router.push(edit/${postId}) and keep track of the changes in history.

Router structure

app
|-- (tabs)
|   |-- post
|   |-- comments
|   |-- ...
|-- post
|   |--[edit].tsx
|-- ...