Reputation: 35
Really sorry, I know this has been posted before but I just didn't understand how the answers related to my problem. I'm very new to react and need a bit more help than I could find.
My app project has reviews like this;
const restaurantData = [
{
id: 1,
restaurantName: "Restaurant 1",
address: "4, Dolphin Way, Swansea SA10 5BZ",
lat: 48.8737815,
long: 2.3501649,
ratings: [{ ratingID: 1, stars: 2, comment: "Terrible service, Yikes!" }],
},
];
And I have accessed the data no problem like this;
function RestaurantItem({ restaurant }) {
return (
<div className="restaurantItem" id={restaurant.id}>
<h2 className="AsideHeader">{restaurant.restaurantName}</h2>
<p className="AsideAddress">{restaurant.address} </p>
</div>
);
}
I would basically like to access the review data specifically by doing something like this;
<div>
<p>{restaurant.ratings.stars} STAR : </p> {restaurant.ratings.comment}
</div>
But I am not having any luck. Can someone explain what I am doing wrong and how to address it ? Or even what else I would call this to look up the solution?
Thank You !
Upvotes: 1
Views: 135
Reputation: 36
You call props on array, but you need call prop on element of array.
If the ratings property always has one element, then you can write it like this, but it will be a crutch
function RestaurantItem({ restaurant }) {
return (
<div className="restaurantItem" id={restaurant.id}>
<h2 className="AsideHeader">{restaurant.restaurantName}</h2>
<p className="AsideAddress">{restaurant.address} </p>
</div>
<div>
<p>{restaurant.ratings[0].stars} STAR : </p> {restaurant.ratings[0].comment}
</div>
);
}
@lich reported correctly, to work with an array, you must use the map method
Upvotes: 0
Reputation: 386
Since restaurant.ratings is a list you can't display it just like a string.
You could display them like this:
<div>
{restaurant.ratings.map((rating, index) => (
<p key={"rating-" + rating.ratingID}>
{rating.stars + " STAR : " + reating.comment}
</p>
))}
</div>
The map method of the list iterates over every element and returns each as "described" by the anonymous method as a JSX Element.
Upvotes: 1
Reputation: 1325
Inside your const restaurantData
the ratings
is an array. If there is only 1 rating then remove the array:
ratings: { ratingID: 1, stars: 2, comment: "Terrible service, Yikes!" }
If there will be multiple ratings then use .map
to loop every single one.
{restaurant.ratings.map((rating) => (
<div key={rating.ratingID}>
<p>{rating.stars} STAR : </p> {rating.comment}
</div>
))}
Upvotes: 1
Reputation: 912
ratings
is an array, so you can't access the data as ratings.stars
or ratings.comment
.
An approach would be to use map
to iterate through the ratings and display all of them for that specific restaurant.
<div>
{restaurant.ratings.map((rating) => (
<p key={rating.ratingID}>{`${rating.stars} STAR: ${rating.comment}`}</p>
))}
</div>
Upvotes: 1