1

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.

2 Answers 2

3

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"/>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. it is showing the alerts. But the alerts run as soon as the program runs.
@craftdeer change onPress to onPress={() => this.mybuttonclick(item.original_title)}
Awesome. Could you explain the arrow function in your last comment?
@craftdeer this article explains it very thoroughly.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.