I have an object-array. Each object has another object as attribute.
If I'm passing the object itself by prop the information gets passed but if I'm passing the inner-object only the information gets lost and it gets undefined
und I can't read its values.
Here is my code:
const cards = [
{
id: 1,
title: "Example 01",
description:
"Lorem, ipsum dolor sit amet consectetur adipisicing elit. Explicabo saepe harum delectus recusandae possimus officiis, eligendi praesentium dicta officia numquam at quidem doloribus sed odit fugiat deserunt iure? Cum vero exercitationem ea non aspernatur eos accusamus consequatur enim beatae, delectus laborum in illum eaque nesciunt nam cumque maiores debitis doloremque et fugiat labore voluptates tenetur at. Nesciunt, ea dignissimos! Sunt nihil deserunt, vitae id alias quidem iste accusamus. Doloribus, similique.",
stats: { rating: 5, reviewCount: 30 },
},
];
export default function List() {
return (
<div>
{cards.map(
(card) => (
console.log("card in List:", card),
console.log("stats in List:", card.stats),
(<Card key={card.id} stats={cards.stats} card={card} />)
)
)}
</div>
);
}
function Card({ stats, card }) {
console.log("card in Card: ", card);
console.log("stats in Card: ", stats);
}
Output:
card in List: {id: 1, title: 'Example 01', description: 'Lorem, ipsum dolor sit amet consectetur adipisicin…lias quidem iste accusamus. Doloribus, similique.', stats: {…}} description: "Lorem, ipsum..." id: 1 stats: {rating: 5, reviewCount: 30} title: "Example 01" [[Prototype]]: Object
stats in List: {rating: 5, reviewCount: 30}
card in Card: {id: 1, title: 'Example 01', description: 'Lorem, ipsum dolor sit amet consectetur adipisicin…lias quidem iste accusamus. Doloribus, similique.', stats: {…}} description: "Lorem, ipsum..." id: 1 stats: {rating: 5, reviewCount: 30} title: "Example 01" [[Prototype]]: Object
stats in Card: undefined
And I also get the error:
Uncaught TypeError: Cannot read properties of undefined (reading 'rating')
Why are you not able to pass inner-objects via props?
CodePudding user response:
Minor mistake in your code. It should be card.stats
instead of cards.stats
.
<Card key={card.id} stats={card.stats} card={card} />
CodePudding user response:
Your map run on 'card'. But you using 'cards' for your stats prop.
export default function List() {
return (
<div>
{cards.map(
(card) => (
console.log("card in List:", card),
console.log("stats in List:", card.stats),
(<Card key={card.id} stats={card.stats} card={card} />)
)
)}
</div>
);
}
You can use like this.