I am trying to generate a Card from JSON data using Map function in React Native.
I want to be able to navigate to another page by clicking on this card.
This is the solution I am trying:
function display() {
return restaurant.map((item) => {
return(
<TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}>
<View style={styles.card}>
<View style={styles.cardHeadText}>
<Text style={styles.title}>
{ item.name }
</Text>
<Text>
{ item.type }
</Text>
</View>
</View>
</TouchableHighlight>
);
});
}
class RestaurantCard extends Component {
render() {
return (
<View style={styles.container}>
{display()}
</View>
);
}
}
But I get following error:
Undefined is not an object (evaluating '_this.props.navigation')
What am I doing wrong?
CodePudding user response:
You can pass this
as an argument to the map
function as described in the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
function display() {
return restaurant.map((item) => {
return(
<TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}>
<View style={styles.card}>
<View style={styles.cardHeadText}>
<Text style={styles.title}>
{ item.name }
</Text>
<Text>
{ item.type }
</Text>
</View>
</View>
</TouchableHighlight>
);
}, this); // over here
}
CodePudding user response:
You can try it :) Ive passed navigation as a props in display function, destructing it and re-using as a short curt to acess this.props.navigation..
Extracting the logic of the click in a handler
made it easy to read and control, you can add verifies and other things a lot more easier.
function display(props) {
const { navigation } = props
const handlerClick = (item) => {
/*
all the content of item (name, and type) will be passed in
props of the other page component
*/
navigation.navigate("Restaurant", { ...item})
}
return restaurant.map((item) => {
return(
<TouchableHighlight onPress={() => handlerClick(item)}>
<View style={styles.card}>
<View style={styles.cardHeadText}>
<Text style={styles.title}>
{ item.name }
</Text>
<Text>
{ item.type }
</Text>
</View>
</View>
</TouchableHighlight>
);
});
}
class RestaurantCard extends Component {
render() {
return (
<View style={styles.container}>
{display(this.props.navigation)}
</View>
);
}
}