I have a list of products and need to navigate to each product from that list and show data passed from HomeScreen do DetailsScreen.I'm trying to navigate between screens using react-navigation.
I pass bellow JSON data as a state when I navigate to DetailsScreen. Can't find the right solution to navigate to a clicked product.
How can I pass just one item of the array to next screen so when you open DetailsScreen you always have right data? Or can I somehow navigate with an index to exactly details screen?
I have some JSON data :
{ "products" : [{
"id": "0",
"imageUrl":
"https://c.static-nike.com/a/images/t_PDP_1728_v1/f_auto/bfbtp31oaoe1haptpdcz/free-tr-flyknit-3-training-shoe-rJTGVbmL.jpg",
"title": "Nike Free TR Flyknit 3",
"price": "60$",
"userPhone": "041-425-900",
"userEmail": "adam@gmail.com"
},
{
"id": "1",
"imageUrl":
"https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/dhw4wxp9ebyef1q35f4g/metcon-4-cross-training-weightlifting-shoe-1qTbMObn.jpg",
"title": "Nike Metcon 4",
"price": "127$",
"userPhone": "041-125-400",
"userEmail": "davids@gmail.com"
},
{
"id": "2",
"imageUrl":
"https://c.static-nike.com/a/images/t_PDP_1728_v1/f_auto/xzei8hswzsvdv1xlsd5e/air-max-90-leather-shoe-xqTPGEVE.jpg",
"title": "Nike Air Max 90 Leather",
"price": "200$",
"userPhone": "041-211-320",
"userEmail": "ragnar@gmail.com"
}]
}
HomeScreen:
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
data: data.products,
};
}
_keyExtractor = (item, index) => item.id;
//Bellow is navigation method and passing JSON as state
openDetails = () => {
this.props.navigation.navigate("Details", {
data: this.state.data,
});
};
renderProduct = ({ item, index }) => {
console.log('index je', this.state.index);
return (
<Item
itemTitle={item.title}
openDetails={this.openDetails}
itemUrl={item.imageUrl}
data={this.state.data}
/>
);
};
render() {
return (
<FlatList
data={this.state.data}
renderItem={this.renderProduct}
keyExtractor={this._keyExtractor}
/>
);
}
}
export default HomeScreen;
DetailsScreen:
class DetailsScreen extends React.Component {
render() {
const { params } = this.props.navigation.state;
const data = params ? params.data : null;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>{JSON.stringify(data.title)}</Text>
</View>
);
}
}
export default withNavigation(DetailsScreen);
Assuming that your data is being passed as the navigation and the components are connected, and your Item Component is your DetailsScreen therefore you can do the following
DetailsScreen.js
Wrap your view in
TouchableOpacity
to accessTouchable
events