I have a stack layout at the root of the app, which in turn has other nested stacks. The initial screen is app/index. Let’s say that in one of these nested stacks, like (mainScreen), I want to go back to app/index, which is the initial screen.
When I use router.push(‘/’) or router.replace(‘/’) it goes back to (mainScreen)/index and not app/index. The documentation doesn’t seem to explain anything about it.
I can’t use route.back because I wouldn’t always be on the first screen right after navigating from the initial screen, the (mainScreen) has several screens, so if I’m not on the first one, it won’t work.
2
import { useRouter } from 'expo-router';
const router = useRouter();
const goToRoot = (): void => {
router.dismissAll()
};
1
I came across the same issue recently and was able to find a solution to it.
so for some reason, the expo-router has this weird way of handling navigation (probably a bug).
when you use the router.push("/")
or router.replace("/")
or any method you are using to navigate in expo-router it resolves it by navigating to the closest index file on the application stack.
In your case, it would take you to mainScreen/index
if you do the navigation in the mainScreen
stack.
the solution I used to resolve this for now(pending when the issue has been resolved) is to make sure that there is only one index file on the application routing stack(app
folder) which would serve as the root app/index
that way whenever you use router.push("/")
or router.replace("/")
it takes you to the root app/index
.
all other index files should be changed to something else and then to set the initial route for that layout you could add an unstable_setting
setup like this :
import { Stack } from "expo-router";
export const unstable_settings = {
initialRouteName: "initial-route", // set the initial route here
};
export default function RouteLayout() {
return (
<Stack
screenOptions={{
headerShown: false,
gestureEnabled: false,
}}
>
<Stack.Screen name="initial-route" />
<Stack.Screen name="route-2" />
<Stack.Screen name="(group-route)" />
</Stack>
);
}
I hope this resolves your issue.
1