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>
)
}
}
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>
);
)}
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>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With