Reputation: 8478
I want to print Props passed in to my component GroceryListItem
from parent component GroceryList
My Code of GroceryList
:
class GroceryList extends React.Component {
constructor(props) {
super(props);
this.state = {
groceries: [ { name: "Apples"}, {name: "Orange"}, {name : "Banana"} ]
};
}
render() {
const element = [];
for(var index = 0; index < this.state.groceries.length; index++) {
element.push(<ul><GroceryListItem grocery={this.state.groceries[index]} /></ul>);
}
return (
<div>
{element}
</div>
);
}
}
My Code of GroceryListItem
:
class GroceryListItem extends React.Component {
constructor(props) {
super(props);
}
render() {
// I want to print the props passed here, but below code is not printing it
console.log("Hi from GroceryListItem " + this.props.grocery);
return (
<li>
{this.props.grocery}
</li>
);
}
}
The console prints :
Hi from GroceryListItem [object Object]
The console shows [object Object]
But not exact values like Apples, Orange, Banana
. How can I print all values from props
Upvotes: 0
Views: 594
Reputation: 3933
You need to access the name
property of your object
class GroceryListItem extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log("Hi from GroceryListItem " + this.props.grocery.name);
return (
<li>
{this.props.grocery.name}
</li>
);
}
}
Upvotes: 3