Home > Net >  React Native - navigation is undefined
React Native - navigation is undefined

Time:05-05

I have "ProfileScreen" declared in the App.js

function App({ navigation }) {
return (
    <>
    <StatusBar hidden />
    <NavigationContainer>
    <Stack.Navigator initialRouteName="Home">
        
        <Stack.Screen 
        ...            
        component={HomeScreen} 
        ...
        />

        <Stack.Screen 
        ...
        component={FeedScreen}
        ...
        />

        <Stack.Screen 
        ... 
        component={ProfileScreen} 
        ...
        />

    </Stack.Navigator>
    </NavigationContainer>
    </>
);
}

I access ProfileScreen inside FeedScreen.js

export const ProfileScreen = () => {
return(
  <Text style={{ textAlign: "left", color: "black", fontSize: 24, fontFamily: 'Montserrat_100Thin_Italic' }}>
    Hello
  </Text>
);
}

Inside FeedScreen.js I want to navigate to ProfileScreen:

const Item = ({ item }, { navigation }) => {
return (
  <>
    <TouchableOpacity onPress={() => navigation.navigate("ProfileScreen")}>
      <Text style={{ textAlign: "left", color: "white", fontSize: 24, fontFamily: 'Montserrat_100Thin_Italic' }}>
        <Image
          style={{ alignSelf: "center", borderRadius: 50 }}
          source={{ uri: item.profile_picture, width: 48, height: 48 }}
        />
        {item.username}
      </Text>
    </TouchableOpacity>
  </>
);
};

Unfortunately, everything returns Undefined is not an object (evaluating 'navigation.navigate')

CodePudding user response:

For an easy solution use the hook useNavigation inside your Item component as a following:

import { useNavigation } from '@react-navigation/native'; 

const Item = ({item}) => {
  const navigation = useNavigation();
  return (
    <TouchableOpacity onPress={() => navigation.navigate('ProfileScreen')}>
      <Text
        style={{
          textAlign: 'left',
          color: 'white',
          fontSize: 24,
          fontFamily: 'Montserrat_100Thin_Italic',
        }}>
        <Image
          style={{alignSelf: 'center', borderRadius: 50}}
          source={{uri: item.profile_picture, width: 48, height: 48}}
        />
        {item.username}
      </Text>
    </TouchableOpacity>
  );
};

CodePudding user response:

Your syntax was wrong for using navigation prop inside FeedScreen It should be like this

const Item = ({ item , navigation }) => {

  • Related