Why is React Native App.js navigation undefined in App.js?

Viewed 3831

export default function App ({navigation})

There is a function that starts with and contains <Stack.Navigator>.

But when I want to use the navigation feature and use "navigation.navigate ('Lead') in onPress

TypeError: undefined is not an object evaluating react navigation

I get an error. My English is not very good. Please help me on this topic. Now I'm adding the sample codes to you.

import * as React from 'react';
import { StyleSheet, AsyncStorage, Alert, View, Image, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { ApplicationProvider, Layout, Input, Button, Text, Spinner, IconRegistry, Icon } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';
import * as eva from '@eva-design/eva';
import LinkingConfiguration from './navigation/LinkingConfiguration';
import * as axios from 'axios';
import Base64 from './components/Base64';
import LeadScreen from './screens/LeadScreen';
import AddLeadScreen from './screens/AddLeadScreen';
import TabBarIcon from './components/TabBarIcon';
import HomeScreen from './screens/HomeScreen';
import CampaignsScreen from './screens/CampaignsScreen';
import MenuScreen from './screens/MenuScreen';

const Stack = createStackNavigator();

export default function App({ navigation }) {  
  const logout = async () => {
    await AsyncStorage.removeItem('token');    
    dispatch({ type: 'SIGN_OUT' });
  };
  
  return (    
    <>
      <IconRegistry icons={EvaIconsPack} />
      <ApplicationProvider {...eva} theme={eva.light}>        
          <Layout style={styles.container}>
            <AuthContext.Provider value={authContext}>
              <NavigationContainer linking={LinkingConfiguration}>
                <Stack.Navigator>
                  {state.isLoading ? (
                    // We haven't finished checking for the token yet
                    <Stack.Screen name="Splash" component={SplashScreen} options={{ headerShown: false }} /> 
                    ) : state.token == null ? (
                    // No token found, user isn't signed in
                    <>
                      <Stack.Screen name="Login" component={LoginScreen} options={{ title: 'Oturum Açın' }} />                      
                    </>
                    ) : (
                    // User is signed in
                    <>
                    <Stack.Screen name="User" component={UserScreen} options={{
                        headerStyle: { backgroundColor: '#e8a200' },
                        headerTintColor: 'white',
                        headerTitleStyle: { color: '#fff' },
                        headerRight: () => (
                          <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={() => logout() } style={{ marginRight: 12 }}>
                            <Icon
                              style={styles.icon}
                              fill='#FFFFFF'
                              name='power-outline'
                            />
                          </TouchableOpacity>
                        )
                      }} />

                      <Stack.Screen name="Lead" component={LeadScreen} options={{
                        title: 'Müşteri Adayları',
                        headerStyle: { backgroundColor: '#e8a200' },
                        headerTintColor: 'white',
                        headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
                        headerRight: () => (
                          <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => console.log(navigation) } style={{ marginRight: 12 }}>
                            <Icon
                              style={styles.icon}
                              fill='#FFFFFF'
                              name='plus-outline'
                            />
                          </TouchableOpacity>
                      )}} />

                      <Stack.Screen name="AddLead" component={AddLeadScreen} options={{ title: 'Müşteri Adayı Ekle' }} />
                    </>
                  )}              
                </Stack.Navigator>
              </NavigationContainer>
            </AuthContext.Provider>
        </Layout>
      </ApplicationProvider>
    </>
  );
}
4 Answers

You can pass the navigation or rout prop into options in the stack.screen like this

options={({navigation})=>({
    'Your code here'
})}

I have edited it with your code for you.

        <Stack.Screen name="Lead" component={LeadScreen}
         options={({ navigation }) => ({
             title: 'Müşteri Adayları',
             headerStyle: { backgroundColor: '#e8a200' },
             headerTintColor: 'white',
             headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
             headerRight: () => (
                <TouchableOpacity activeOpacity={0.4} 
                   underlayColor='transparent' onPress={() => 
                   console.log(navigation)} style={{ marginRight: 12 }}>
                    <Icon
                       style={styles.icon}
                          fill='#FFFFFF'
                          name='plus-outline'
                      />
                  </TouchableOpacity>
                  )
         })} />

First, I think the navigation here is unnecessary, you can remove it.

export default function App({ navigation }) {  

In your screen components, ie. UserScreen, you can use navigation like so

function UserScreen({navigation}) {
  // ...some codes
  navigation.navigate('WHERE_TO_GO');
  // ...some other codes
}

You could also use navigation without passing it to the props.

First you need to import useNavigation

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

And then, in your component

function UserScreen() {
  const nav = useNavigation();
  // ...some codes
  nav.navigate('WHERE_TO_GO');
  // ...some other codes
}

You could get more details here https://reactnavigation.org/docs/use-navigation/

For the onPress function of Lead screen,

<Stack.Screen name="Lead" component={LeadScreen} options={({ navigation }) => ({
  title: 'Müşteri Adayları',
  headerStyle: { backgroundColor: '#e8a200' },
  headerTintColor: 'white',
  headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
  headerRight: () => (
    <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => navigation.navigate('WHERE_TO_GO') } style={{ marginRight: 12 }}>
      <Icon
        style={styles.icon}
        fill='#FFFFFF'
        name='plus-outline'
      />
    </TouchableOpacity>
)})} />

You should use useLinkProps to solve this issue:

import { useLinkProps } from '@react-navigation/stack';

And this is an example on how to write code which uses it:

const LinkButton = ({ to, action, children, ...rest }) => {
  const { onPress, ...props } = useLinkProps({ to, action });

I have tried everything but this worked for me. Make a function in your app.js and pass props then access using props.navigation like below.

function CustomDrawerContent**(props)** {
.....
    
  logOut = () => {
    AsyncStorage.clear(); 
    **props.navigation.navigate("Login");**
  };
.....
}
Related