Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key and item onPress TouchableOpacity when items are map

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>
        )
    }
}
like image 734
Bhaumik Surani Avatar asked Aug 03 '18 07:08

Bhaumik Surani


2 Answers

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>
  );
)}
like image 130
hsz Avatar answered Oct 04 '22 22:10

hsz


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>
        )
    }
}
like image 37
PrashanD Avatar answered Oct 04 '22 21:10

PrashanD