Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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}
<Text>{item.location}</Text>
</View>
</View>
</TouchableOpacity>
Usage:
<WebsiteFlatlist data={places} onPress={() =>{this._onPress(item.location)}}/>
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)}
<Text>{item.location}</Text>
</View>
</View>
</TouchableOpacity>
Usage:
<WebsiteFlatlist data={places} onPress={this._onPress}/>
_onPress = async (places) => {
console.log(places)
–
Only pass the functional reference in your <WebsiteFlatlist onPress={this._onPress}>
. While in the common component make some changes.
Separate the renderItem component.
Use function to renderItem inside the component.
const renderItem = (item) => {
return (
<TouchableOpacity onPress={()=>props.onPress(item)}>
<Text>{item.location}</Text>
</View>
</View>
</TouchableOpacity>
<FlatList
data={props.data}
keyExtractor={(item, index) => index.toString()}
renderItem={
({ item }) => (this.renderItem(item))
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.