reactjsreact-nativejsx

clickable Flat list items in React Native


I have a flat list that displays a list of item, I would like to make each item clickable. My render function looks like this, and it works without any issue, except that it is not clickable

  render() {
    return (
      <FlatList
        data={formatData(data, numColumns)}
        style={styles.container}
        renderItem={this.renderItem}
        numColumns={numColumns}
      />

    );
  }

I have tried to do something similar to this but it is giving me an error, any idea what's wrong with my code?

      <FlatList
        data={formatData(data, numColumns)}
        style={styles.container}
        renderItem={({this.renderItem})  => (
        <TouchableHighlight
        onPress={() => console.log("hello")}>
           </TouchableHighlight>
        )}
        numColumns={numColumns}
      />

Solution

  • You can do like this :

    renderItem with TouchableOpacity. Make sure to import it from react native.

    import { TouchableOpacity } from "react-native";
    import Icon from 'react-native-vector-icons/FontAwesome5';
    ...
    ...
    
    render() {
      return (
        <FlatList
          data={formatData(data, numColumns)}
          style={styles.container}
          renderItem={({item ,index}) => (
            <TouchableOpacity 
              key={index.toString()} 
              onPress={() => console.log("clicked")}
            >
              <Icon name={item} color="red"/>
            </TouchableOpacity>
          )}
          numColumns={numColumns}
          key={numColumns.toString()} // if you want to use dynamic numColumns then you have to use key props
        />
      );
    }