6

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>
        )
    }
}
Deepak
  • 724
  • 4
  • 13
Bhaumik Surani
  • 1,730
  • 3
  • 19
  • 40

2 Answers2

8

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>
  );
)}
hsz
  • 148,279
  • 62
  • 259
  • 315
3

You can also use curried functions for this:

export default class MyLanguages extends Component {
    constructor(props) {
      super(props);
      this.state = {
        languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
      };
    }

   // Curried function (A function which, when invoked (with an argument), returns another function that depends on the argument
   onPressHandler = key => event => {
      console.log(key, event)
   }

    render() {
        return (
            <View style={styles.container}>
                {this.state.languageData.map( (item,index) => {

                    // Invoke the curried function with the index as the argument for the key paremeter,
                    // which returns another function which is set as the onPress event handler
                    return (
                        <TouchableOpacity
                            key={index}
                            onPress = {this.onPressHandler(index)}
                        >
                            <Text style={MyStyle.appFontStyle2}>{item}</Text>
                        </TouchableOpacity>
                    )}
                )}
            </View>
        )
    }
}
PrashanD
  • 2,643
  • 4
  • 28
  • 58