Get key and item onPress TouchableOpacity when items are map

Bhaumik Surani picture Bhaumik Surani · Aug 3, 2018 · Viewed 8.6k times · Source

In below code items are rendered properly and working
But When I Press TouchableOpacity it returns event.
I Used JSON.stringify(event.nativeEvent) but not working

I want to get the key value that set on TouchableOpacity and that item Data.

export default class MyLanguages extends Component {
    constructor(props) {
      super(props);
      this.state = {
        languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
      };
    }
    render() {
        return (
            <View style={styles.container}>
                {this.state.languageData.map( (item,index) => {
                    return (
                        <TouchableOpacity key={index}
                            onPress={ (event)=>{
                                alert(event.nativeEvent)
                            }}>
                            <Text style={MyStyle.appFontStyle2}>{item}</Text>
                        </TouchableOpacity>
                    )}
                )}
            </View>
        )
    }
}

Answer

hsz picture hsz · Aug 3, 2018

item and index are still in the scope of onPress callback, so you can refer to them directly:

{this.state.languageData.map((item, index) => {
  return (
    <TouchableOpacity
      key={index}
      onPress={event => {
        alert(`${index}: ${item}`);
      }}
    >
      <Text style={MyStyle.appFontStyle2}>{item}</Text>
    </TouchableOpacity>
  );
)}