Nabin Dhakal
Nabin Dhakal

Reputation: 2192

Implement onPress on Flatlist item

I am trying to send the data of the flatlist items when clicked and set to another class.The ontouch is working but I am having the error below in the image. Also how can I send the data of api to the other class and get from another class? I have implemented as follows:

enter image description here

export default class FlatSpeakers extends Component {

constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [],selectedItem: null, }
   const { navigate } = this.props.navigation;
}

onPressItem = () => {
  navigate('SpeakersClick')
};

componentDidMount() {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
        .then(res => {
            this.setState({
                isLoading: false,
                data: res.data,
            })
        })
}

renderItem({ item }) {
    return (
        <TouchableOpacity onPress={()=>this.onPressItem(item)} >
            <Card>
                <CardSection>
                    <View style={styles.thumbnailContainerStyle}>
                        <Image
                            style={styles.thumbnailStyle}
                            source={{ uri: item.image }}
                        />
                    </View>
                    <View style={styles.headerContentStyle}>
                        <Text style={styles.headerTextStyle}>{item.title}</Text>
                        <Text>{item.artist}</Text>
                    </View>
                </CardSection>
            </Card>
        </TouchableOpacity>
    )
}

render() {
    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={this.renderItem}
                    keyExtractor={(item, index) => index}
                    onPress={this.onPressItem}
                />
            </View>

    );
}
}

Upvotes: 0

Views: 598

Answers (2)

Izzuddiin
Izzuddiin

Reputation: 265

try to put this.onPressItem = this.onPressItem.bind(this) on constructor(props)

Upvotes: 1

mmmatey
mmmatey

Reputation: 684

Problem in your code is, that you are calling same method from two sides - on one side you are passing arguments in it on another side you are not passing arguments. If you wan't to have both cases covered you should change you onPressFunction, to accept arguments - in your case item:

onPressItem = (item) => {
  navigate('SpeakersClick')
};

Upvotes: 1

Related Questions