Home > Net >  React Native Navigation : can't navigate between stack when inside a function from another file
React Native Navigation : can't navigate between stack when inside a function from another file

Time:10-28

I have been able to fix my problem now thanks to Stephan answer

I'm having a bit of problem with how navigation works in React Native.
Basically what I'm trying to do is this :\

While I'm in the Home stack navigate to the SubFeed stack from the Feed function called in Home.

Here is my code

import Feed from './Feed'

function Home({ navigation }) {

return (
    <ScrollView>
        <Feed/>
    </ScrollView>

Home.js

function Feed({ navigation }) {

return (
    <View>
        <Button title="nav1" 
                onPress={() => navigation.navigate('SubFeed')}/>
        <Button title="nav2" 
                onPress={() => navigation.navigate('Home', {screen: 'SubFeed'})}/>
    </View>

Feed.js

In my App.js I create my stacks like this:

<NavigationContainer>
  <StatusBar
    backgroundColor="#ffa31a" />
  <Stack.Navigator initialRouteName="Project">
    <Stack.Screen name="Project" component={Home}/>
    <Stack.Screen name="Feed" component={Feed} />
    <Stack.Screen name="SubFeed" component={SubFeed} />
  </Stack.Navigator>
</NavigationContainer>

App.js

I found that in other file where I use navigation I don't need to import anything to make the navigation works as long as I have { navigation } in my function.


The problem is that whenever I try to press either of the buttons I keep getting the same error:

TypeError: undefined is not an object (evaluating 'navigation.navigate') \

When I search for an answer I keep seeing things about screens but it doesn't seem to be working in my case.

  • I think the problem comes from the fact that I try to change the stack outside from home, but I can't understand why.

If you have any suggestion or even better the answer to my problem I would really appreciate it.

CodePudding user response:

In your code, Feed component doesn't know about navigation property. So, you can pass it as a prop form the parent Home or you can use react-navigation-hooks and use const { navigate } = useNavigation(); inside Feed component.

  • Related