Skip to content

this.props.navigation.navigate() not working

I want the app to check if there’s a user logged in (firebase authentication). If there is, navigate to one page (react navigation v5), if there isn’t, to another.

I have the following code:

In App.js

//import navigation + screens

const Stack = createStackNavigator();
const MaterialBottomTabs = createMaterialBottomTabNavigator();

class App extends React.Component {

    AuthStack = () => {
      <Stack.Navigator>
        <Stack.Screen name="login" component={LoginScreen} />
        <Stack.Screen name="register" component={RegisterScreen} />
      </Stack.Navigator>
    }

createBottomTabs = () => {
      return <MaterialBottomTabs.Navigator>
          <MaterialBottomTabs.Screen name="first" component={firstScreen} />
          <MaterialBottomTabs.Screen name="second" component={secondScreen} />
        </MaterialBottomTabs.Navigator>
    }
render(){
      return(
        <LoadingScreen />
      )
    }
}

export default App;

In Loading.js

import React from "react";
import { Text, SafeAreaView } from "react-native";
import * as firebase from "firebase";
import {AuthStack, createBottomTabs} from "./App.js";

class LoadingScreen extends React.Component {

  componentDidMount() {
    firebase.auth().onAuthStateChanged((user) => {
      this.props.navigation.navigate(user ? createBottomTabs : AuthStack);
    });
  }
  render() {
    return (
      <SafeAreaView>
        <Text>
          Waiting...
        </Text>
      </SafeAreaView>
    );
  }
}

export default LoadingScreen;

I get an error which says:

TypeError: undefined is not an object (evaluating ‘_this.props.navigation.navigate’)

Answer

The navigation prop is not passed into all components, only screen components receive this prop automatically! If, however, you wish to access the navigation prop in any of your components, you may use the useNavigation hook.

Here is an example from the docs

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}