Reputation: 1250
I'm new to React, I just followed a tutorial step by step and got other results. The error message I'm getting is:
Cannot read property 'name' of undefined.
The question is why is name undefined? I added objects that I need to show on a page a list.
Here is my code where I fall:
import React, { Component } from "react";
class UserItem extends Component {
render() {
return (
<li className="UserLI">
{this.props.users.name} is {this.props.users.age} years old.
</li>
);
}
}
export default UserItem;
And here is where I call the above code:
class Users extends Component {
render() {
let userItem;
if (this.props.users) {
userItem = this.props.users.map(user => {
console.log(user);
return <UserItem key={user.id} user={user} />;
});
}
return <div classNname="Users">{userItem}</div>;
}
}
my JSON data
this.setState({users:[
{
id:0,
name: "karam",
age:22
},
{
id:1,
name: "ayoub",
age:23
},
{
id:2,
name: "tarek",
age:21
}
]});
Upvotes: 2
Views: 10850
Reputation: 193
The issue is your data not coming at the moment the code get render. you can fix that issue by adding basic validation.
class UserItem extends Component {
render() {
return (
<li className="UserLI">
{this.props.users && this.props.users.name} is {this.props.users && this.props.users.age} years old.
</li>
);
}
}
Upvotes: 2
Reputation: 281686
You need to access name
and age
from this.props.user
and not this.props.users
, since you are passing the data as prop user
class UserItem extends Component {
render() {
return(
<li className="UserLI">
{this.props.user.name} is {this.props.user.age} years old.
</li>
)
}
}
export default UserItem;
Upvotes: 0
Reputation: 36179
You pass a user
prop:
<UserItem key={user.id} user={user} />
But you try to access it as users
<li className="UserLI">
{this.props.users.name} is {this.props.users.age} years old.
</li>
It's a typo. Fix:
<li className="UserLI">
{this.props.user.name} is {this.props.user.age} years old.
</li>
Upvotes: 0