mlodykk
mlodykk

Reputation: 28

TypeError: undefined is not an object (evaluating 'navigation.navigate'), cannot navigate from component placed on screen to another screen

im trying to navigate to another screen from component placed on HomePage, but the code below doesnt work. I think i tried all of the solutions that i found in the internet, but none of them seems to be working. (The button on HomePage is working)

HomePage:

import * as React from 'react';
import { StyleSheet,View ,Button} from 'react-native';
import RecipeButton from '../components/recipeButton';
import recipes from '../../assets/data/recipes';
import { StatusBar } from 'expo-status-bar';

export default function HomePage({navigation}: {navigation: any}) {
  return(
    <View style={styles.container}>
    <StatusBar style="light" backgroundColor="black" translucent={false} />
    <FlatList 
      style={{width:'100%'}}
      data={recipes}
      renderItem={({ item }) => <RecipeButton item={item} />}
    />
    <Button title='navigate to recipe' onPress={() => {
      navigation.navigate("Recipe")
    }} />
  </View>
  )
}

component script:

import React from 'react';
import { Image, View, Text, Pressable} from 'react-native';
import { FontAwesome } from '@expo/vector-icons';
import styles from './styles';

interface recipeButtonProps {
    item: {
        image: string,
    }
}


const RecipeButton = ({ item }: recipeButtonProps, {navigation}: {navigation: any}) => {

    const onPress = () => {
        navigation.navigate("Recipe")
    }

    return (
        <View style={styles.root}>
            <Image style={styles.image} source={{ uri: item.image }} />

            <Pressable
             style={({pressed}) => [
                {backgroundColor: pressed ? '#D3D3D3' : 'white'},
                styles.nonImageContainer
            ]} 
            onPress={() => {
                onPress();
            }}>
            </Pressable>
        </View>
    );
};

export default RecipeButton;

Upvotes: 0

Views: 213

Answers (1)

dtamaas
dtamaas

Reputation: 46

I think RecipeButton is not in the context of the navigator, so it doesn't get the navigation prop.

Try to use the useNavigation() hook like this:

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


const RecipeButton = ({ item }: recipeButtonProps) => {
    const navigation = useNavigation();
    
    const onPress = () => {
        navigation.navigate("Recipe")
    }

    ...
};

export default RecipeButton;

Upvotes: 1

Related Questions