endlessCode
endlessCode

Reputation: 1405

react native flatlist item is not defined

I am trying to make my flatlist a reusable component but i get an error

item is not defined.

How can i let my onpress function have access to item inside my reusable component?

Code:

import React, { Component } from 'react';
import { Text, View } from 'react-native';



export const WebsiteFlatlist = (props) => {
    return(
        <FlatList
        data={props.data}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
            <TouchableOpacity
                onPress={props.onPress}
            >
                <View>
                    <View>
                        <Text>{item.location}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )}
    />

    )

};

Usage:

<WebsiteFlatlist data={places} onPress={() =>{this._onPress(item.location)}}/>




 _onPress = async (places) => {
        console.log(places)
    };                  

Upvotes: 0

Views: 1478

Answers (3)

cauchy
cauchy

Reputation: 1123

Only pass the functional reference in your <WebsiteFlatlist onPress={this._onPress}>. While in the common component make some changes.

  1. Separate the renderItem component.
  2. Use function to renderItem inside the component.
const renderItem = (item) => {
return (
<TouchableOpacity onPress={()=>props.onPress(item)}>
   <View>
       <View>
           <Text>{item.location}</Text>
       </View>
   </View>
</TouchableOpacity>
)}

<FlatList
   data={props.data}
   keyExtractor={(item, index) => index.toString()}
   renderItem={
       ({ item }) => (this.renderItem(item))
   }
/>

Upvotes: 0

Jitesh Manglani
Jitesh Manglani

Reputation: 485

You should bind the item and should directly pass a function to onPress props.

import React, { Component } from 'react';
import { Text, View } from 'react-native';



export const WebsiteFlatlist = (props) => {
    return(
        <FlatList
        data={props.data}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
            <TouchableOpacity
                onPress={props.onPress.bind(null, item)}
            >
                <View>
                    <View>
                        <Text>{item.location}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )}
    />

    )

};

Usage:

<WebsiteFlatlist data={places} onPress={this._onPress}/>

 _onPress = async (places) => {
        console.log(places)
    };  

Upvotes: 1

arjayosma
arjayosma

Reputation: 550

In your onPress function, you should do this:

onPress={this._onPress}

In this way, you are passing the _onPress(location) function as a callback down to your flat list.

Upvotes: 0

Related Questions