craftdeer
craftdeer

Reputation: 1025

Adding a button in a FlatList in React Native

I have a FlatList and I am trying to but a button below the items and when you click on the button it should display the name of the item in an alert.

class TopMovies extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        apiTopLoaded: false,
        topPopularMovies: [],
    }
    this.conditionalTopPopular = this.conditionalTopPopular.bind(this);
    this.mybuttonclick = this.mybuttonclick.bind(this);
}

componentDidMount() {
fetch('someurls')
    .then((response)=>{
        response.json()
            .then((popularMovies) => {
                this.setState({
                    apiTopLoaded: true,
                    topPopularMovies: popularMovies.results,
                })
            })
    })    


mybuttonclick() {
    Alert.alert(item.original_title)
}

conditionalTopPopular() {
    if(this.state.apiTopLoaded===true) {
        return(
                <FlatList
                    horizontal={true}
                    data={this.state.topPopularMovies}
                    renderItem={({ item }) => (
                    <View>

                        <Text>{item.original_title}</Text>
                        <Button onPress={this.mybuttonclick} title="hello"/>
                    </View>
                    )}
                    keyExtractor={item => item.id}
                />
            </View>
        )

    }
}

I can see all the movie names in the list and I see buttons below the movie names, but when I click on it, it says "cant find variable item". The function mybuttonclick should alert the item.original_title prop because it displays correctly in the flatlist. Please help.

Upvotes: 1

Views: 13513

Answers (2)

FaISalBLiNK
FaISalBLiNK

Reputation: 711

You should use the fat arrow function in the onPress like this.

<Button onPress={() => this.mybuttonclick(item.original_title)} title="hello"/>

Upvotes: 0

Ivalo Pajumets
Ivalo Pajumets

Reputation: 449

Change your function like this:

mybuttonclick(movieTitle) {
    Alert.alert(movieTitle)
}

And pass in the the movie title like this:

<Button onPress={this.mybuttonclick(item.original_title)} title="hello"/>

Upvotes: 3

Related Questions