Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-v5

How to go back to another stack in react native navigation v5?


I want to navigate to Home Details which is in HomeStack , from About component which is in AboutStack :

HomeStack.js

export default function HomeStack() {
    return (
        <Stack.Navigator>
            <Stack.Screen component={Home} name="Home" />
            <Stack.Screen component={HomeDetail} name="HomeDetail" />
        </Stack.Navigator>
    );
}

AboutStack.js

export default function AboutStack() {
    return (
        <Stack.Navigator>
            <Stack.Screen component={About} name="About" />
            <Stack.Screen component={AboutDetail} name="AboutDetail" />
        </Stack.Navigator>
    );
}

In About component I navigate to the HomeDetails screen which is in HomeStack navigator :

About.js

<Button
    title="Go Home details"
    onPress={() => navigation.navigate('HomeStack', { screen: 'HomeDetail' })} />

And in HomeDetail screen I try to go back which should go back to the About screen in AboutStack but it goes to Home screen in HomeStack:

HomeDetail.js

    <Button onPress={() => navigation.goBack()} title="Go back" />

It goes back to the root screen of it's own Stack .

This is the navigation version I'm using:

    "@react-navigation/native": "^5.8.10",
    "@react-navigation/stack": "^5.12.8",

How can I go back to About screen in About Stack from HomeDetails screen in HomeStack ?


Solution

  • I solved the problem by passing url params to HomeDetail screen like this :

    About.js

    navigation.navigate('HomeDetail', { url: 'About' })
    

    HomeDetail.js

    function HomeDetail({ navigation, route }) {
        console.log(route);
        return (
            <View style={{ marginTop: 300 }}>
                <Text>Home Detail</Text>
                <Button onPress={() => navigation.navigate(route.params.url)} title="Go back" />
            </View>
        );
    }