user12780786
user12780786

Reputation:

onPress of TouchableOpacity gets called when loading Flatlist

I have a flatlist with a search function. In the next step, I want something to happen when I press within the item. I'm facing the problem that the TouchableOpacity is visible, but nothing happens when it's pressed. I've tried the same with a Button and face the same issue.

Instead of onPress being called when something is pressed, it somehow get's called once the screen loads immediately. If I for example console.log(item.title) I get all the titles in my console log that are currently in the flatlist.

I've tried to figure out what is causing this for many hours, but can't seem to find any reason. Any help is highly appreciated.

I have a Flatlist that is populated with data, set up as follows:

         return (
          <View style={styles.list}>
            <FlatList
              data = {this.state.data}
              renderItem={renderListItem}
              keyExtractor={item => item.id}
              ListHeaderComponent={this.renderHeader}
              
            />
     
          </View>
        );
      }
    }
    
    
       const renderListItem = (item) => {
        return (
        
          <MyTouchable
            id={item.item.id}
            title={item.item.title}
      
         
          />
        );
      }

MyTouchable Component looks like this:

          <View>
       <TouchableOpacity onPress={console.log("Pressed")}>
      <View style={styles.mainView}>
      <View>
       <Text style={styles.text}>{props.id} {props.title}</Text> 
    
       
       </View>
  
      
      </View>
    </TouchableOpacity>
     </View>

Upvotes: 0

Views: 1149

Answers (2)

Koyta
Koyta

Reputation: 50

You can’t write like this: <Component makeThing={myFunc()} />. You should write like that: <Component makeThing={() => myFunc()} /> if you are not using useCallback.

Make sure to read the docs about passing functions to components. You must provide and arrow function, and call your function inside it. Or just use useCallback hook:

const Component = () => {
  const myFunction = useCallback(() => {
    // do something
  }, []);
  return <AnotherComponent coolFunction={myFunction} />
}

Upvotes: 0

Wgg12
Wgg12

Reputation: 181

Try to pass the console.log inside an arrow function

<TouchableOpacity onPress={() => console.log("Pressed")}>
 ...
</TouchableOpacity>

Upvotes: 5

Related Questions