REACT: TypeError: Cannot read property 'name' of undefined

10,123

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>
    );
  }
}
Share:
10,123
Karam Haj
Author by

Karam Haj

Updated on June 27, 2022

Comments

  • Karam Haj
    Karam Haj almost 2 years

    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
      }
    ]});
    
    • Suthan Bala
      Suthan Bala almost 6 years
      {this.props.users.name} is {this.props.users.age} years old. should be {this.props.user.name} is {this.props.user.age} years old.
    • Lennholm
      Lennholm almost 6 years
      You're passing user, not users, to the UserItem component.