Home > database >  React Native - Passing navigation into a child component
React Native - Passing navigation into a child component

Time:10-28

I have a screen with the following:

function Intereset ({ navigation }) {
    function ReturnMyFunction () {
    if (!var.length) {
        return ( <NoILikes /> )
    } else {
        return (
            <FlatList
                data={Ilike}
                keyExtractor={item => item._id}
                ItemSeparatorComponent={() => <Divider />}
                renderItem={UserRow}
            /> 
        )
    }
}

return ( <ReturnILikeOrNoILike /> )
}
export default Interest

Here is my UserRow component below:

const UserRow = ({ item, navigation }) => (
  <TouchableOpacity onPress={() => navigation.navigate("ProfileDetailScreenSingle", { userID: item.likeTo })}>
    <View style={styles.row}>
        <Image style={styles.avatar}
            resizeMode={"cover"}
            source={{ uri: item.likeToProfileImage }}
        />
        <View style={styles.textContainer}>
            <Text style={styles.name}>{item.likeToName}, <Text>{item.likeToAge}</Text></Text>
        </View>
        <Text style={styles.viewProfileText}>View Profile</Text>
        <AntDesign name="right" size={14} color="black" />
    </View>
</TouchableOpacity>

)

When I click on the UserRow to navigate I get the following issue.

enter image description here

CodePudding user response:

FlatList does not pass properties by itself to the render item, you need to manually do that:

const renderUserRow = ({item}) => <UserRow navigation={navigation} item={item}/>
...
 <FlatList
    data={Ilike}
    keyExtractor={item => item._id}
    ItemSeparatorComponent={() => <Divider />}
    renderItem={renderUserRow}
 /> 

CodePudding user response:

Use onPress handler instead and perform navigation on the screen.

const UserRow = ({ item, onPress }) => (
  <TouchableOpacity onPress={onPress}>
...
  </TouchableOpacity>
);

const renderItem = ({ item }) => {
  return (
    <UserRow
      item={item}
      onPress={() => navigation.navigate(...)}
    />
  );
};

<FlatList
  data={Ilike}
  renderItem={renderItem}
...
/>
  • Related