Reputation: 55
I'm trying to pass an array of objects from a parent to a child component as a prop then go map over it and display it in the child component. When I try to map it nothing happens, when I console.log it, it shows my array of objects. What's the difference, what's breaking here?
class ClothingBuyingOptions extends Component {
state = {
size: '',
color: '',
showShoppingBag: false,
items: []
}
addItemToBag = () => {
const { size, color } = this.state;
this.setState({
showShoppingBag: true,
items: [ ...this.state.items, [{ size: size, color: color }]]
});
}
render() {
return (
<div>
<button
onClick={this.addItemToBag}>
Add to Bag
</button>
<ShoppingBag items={this.state.items} />
</div>
);
}
}
class ShoppingBag extends Component {
render() {
const items = this.props.items.map((item, index) =>
<div
key={index}>
<p>{item.size}</p>
<p>{item.color}</p>
</div>
)
console.log(this.props.items)
return (
<div className="container">
{items}
</div>
);
}
}
Upvotes: 2
Views: 81
Reputation: 3594
It's because you're storing an array inside an array, and then trying to access your object properties on an array.
Change this line:
items: [ ...this.state.items, [{ size: size, color: color }]]
To this:
items: [ ...this.state.items, { size: size, color: color }]
The way your state is being constructed with your code is like this:
items: [
[ { size: '', color: ''} ],
[ { size: '', color: ''} ]
]
And you want it to be this:
items: [
{ size: '', color: ''},
{ size: '', color: ''}
]
Also, since your object keys and values are the same, you can define your object as {size, color}
, which is the same as {size: size, color: color}
Upvotes: 1