lucas paes
lucas paes

Reputation: 21

undefined is not an object (evaluating 'navigation.navigate') React Native

I'm have a problem in react navigation, error message "undefined is not an object (evaluating 'navigation.navigate')". Error happens when trying to call a screen by a button from another route

Component code:

     export default function Estruturas({ title, display, navigation }) {
      const [estruturas, setEstruturas] = useState([]);
    
      useEffect(() => {
        async function loadEstruturas() {
          const response = await api.get('/produto/api/estrutura');
    
          setEstruturas(response.data);
        }
        loadEstruturas();
      }, []);
    
    
      return (
...
   
          <ProductList>
            {estruturas.map(estrutura => (
              <Item key={estrutura.id} onPress={()=> navigation.navigate('Pedidos')}> 
...

Routes code:

const Tab = createMaterialBottomTabNavigator();
function MyTabs(){
    return(
        <Tab.Navigator
        barStyle={{ backgroundColor: '#694fad' }} 
        initialRouteName='Feed'   
        activeColor='black' 
        >
            <Tab.Screen 
                name="Início"
                component={Dashboard}
                options={{
                    tabBarLabel: 'Início',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="home"  size={26} />
                    ),
                  }}
            />
            <Tab.Screen 
                name="Pedidos"
                component={Requests}
                options={{
                    tabBarLabel: 'Pedidos',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="assignment"  size={26} />
                    ),
                  }}
            />
        </Tab.Navigator>)}

export default function Routes() {      
    return (
      <NavigationContainer>
        <MyTabs />
      </NavigationContainer>
    );
  }

I tried with Stack but it gave the same error

Upvotes: 0

Views: 124

Answers (1)

Akshay Rao
Akshay Rao

Reputation: 3544

Only the direct child of your navigator stack will have access to the navigation prop. I can see that your component Estruturas is not a direct route so it will not get the navigation prop directly inside the function props. There are 2 ways to get this done and fixed.

  • Either use a withNavigation HOC provided by react-navigation v4 or if you are using v5 then use useNavigation hook.
  • OR you need to pass the navigation prop to the component wherever you are calling this component. This can be done as below:-

export default function Dashboard(props) {
  return (
    <View>
      <Estruturas navigation={props.navigation} />
    </View>
  );
}

Upvotes: 0

Related Questions