Home > Software design >  Error: Couldn't find a navigation object. Is your component inside NavigationContainer?
Error: Couldn't find a navigation object. Is your component inside NavigationContainer?

Time:10-26

I am trying to navigate from my login screen to the home screen using a pressable button. However, the code that I now have gives the following error: Couldn't find a navigation object. Is your component inside NavigationContainer?. The error is aimed on row 8 (const navigation = useNavigation();). LoginButton.js:

import React, { Component } from "react";
import { View, Text, Image, Pressable, Button } from "react-native";
import { useNavigation } from "@react-navigation/native";
import styles from "./styles";
import HomeScreen from "../../screens/Home";

const LoginButton = () => {
  const navigation = useNavigation();

  return (
    <View style={styles.container}>
      <Pressable
        onPress={() => navigation.navigate("Home")}
        style={styles.button}
      >
        <Text style={styles.buttontext}>Login</Text>
      </Pressable>
    </View>
  );
};

export default LoginButton;

The LoginButton is inserted as a component in the LoginItem inside the last <View. LoginItem.js:

import React from "react";
import { View, Text, Image } from "react-native";
import styles from "./styles";
import LoginButton from "../LoginButton";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

const Stack = createNativeStackNavigator();

const LoginItem = (props) => {
  return (
    <View style={styles.logincontainer}>
      {/* Background image of the login screen */}
      <Image
        source={require("../../../assets/images/blue-sky-start-screen.jpg")}
        style={styles.loginbackground}
        blurRadius={4}
      ></Image>
      {/* Title of the login screen */}
      <View style={styles.titlecontainer}>
        <Text style={styles.companytitle}>BestelSnel</Text>
      </View>
      {/* Login button */}
      <View style={styles.loginbutton}>
        <LoginButton></LoginButton>
      </View>
    </View>
  );
};

export default LoginItem;

CodePudding user response:

useNavigation only works if your component is inside of a NavigationContainer and a Navigator like mentioned on the getting-started-page:

https://reactnavigation.org/docs/hello-react-navigation

<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen name="Home" component={HomeScreen} />
  </Stack.Navigator>
</NavigationContainer>

HomeScreen would be your LoginItem

  • Related