JSim
JSim

Reputation: 167

How do I execute a function within a touchable opacity within a flatlist in React Native?

Each item within my flat list is a touchable opacity (an icon). I would like a function to execute when an icon is tapped. This function has been passed as a prop from the parent component and I'm passing the icon data into that prop. I thought this would be straight forward. However when I tap on the icon to open the modal that contains my flat list, the modal doesn't open and I get a warning: 'Cannot update a component from inside the function body of a different component.' I'm confused because I'm executing a function that has been passed as a prop from my parent component. I'm unsure how else I am supposed to do it?

This is the function I want to call on tap (the changeIcon prop is the one causing the issues):

function chosenIcon(selectedIcon) {
  props.changeIcon(selectedIcon);
  props.closeIconList(false);
}

This is the FlatList, and it doesn't seem to like me passing item.item.icon.

<FlatList
  numColumns={3}
  data={ICONS}
  renderItem={(item) => (
    <TouchableOpacity style={styles.item} onPress={chosenIcon(item.item.icon)}>
      <Text style={styles.text}>{item.item.icon}</Text>
    </TouchableOpacity>
  )}
/>

If I comment out the props.changeIcon line in the function and don't pass the data item.item.icon, everything works fine and the modal closes when I select an icon.

I hope that's clear enough! Thank you!

Upvotes: 0

Views: 1128

Answers (1)

Michael Bahl
Michael Bahl

Reputation: 3669

Please try to add a fat arrow function to TouchableOpacity onPress callback.

 <FlatList 
    numColumns = {3}
    data = {ICONS}
    renderItem = {item => (
      <TouchableOpacity style = {styles.item} onPress= {()=> chosenIcon(item.item.icon)}> // add ()=>
         <Text style = {styles.text}>{item.item.icon}</Text>
      </TouchableOpacity>
    )}
  />

Upvotes: 1

Related Questions