Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Native – navigation is undefined

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’)

>Solution :

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>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading