Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 237
Ian McKain Avatar asked Nov 02 '25 05:11

Ian McKain


1 Answers

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
|-- ...
like image 117
agutierrez Avatar answered Nov 04 '25 03:11

agutierrez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!