Saghar Francis
Saghar Francis

Reputation: 47

React Error TypeError: Cannot read property 'name' of undefined

I am learning to react but I am stuck in one issue. I am trying to get the array properties in my Useritem.js file

this is my User.js file

import React, { Component } from 'react'
import Useritems from './Components/Useritems';


const User = () => {
    state = {
        users: [
            { name: 'David', age: '20', Position: 'developer' },
            { name: 'Francis', age: '20', Position: 'Software Engineer' },
        ]
    }
    return (
        <div>
            {this.state.users.map(user => (
                <Useritems user={user} />
            ))}
        </div>
    );
}
export default User

And this is my Useritem.js file


import React from 'react'

const Useritems = ({ user: { name, age, job } }) => {
    return (
        <div>
            <h1>{name}</h1>
            <h2>{age}</h2>
            <h3>{job}</h3>
        </div>
    )

}

export default Useritems

But I am getting an error saying that the property name is not defined

Upvotes: 0

Views: 248

Answers (1)

Flagship1442
Flagship1442

Reputation: 1726

You are using a functional component (as opposed to a class component), so you cannot use this.state. Instead you need to use the hook useState to handle your state, which you can do like this:

import React, { useState } from "react";
import Useritems from "./Components/Useritems";

const initialUsers = [
  { name: "David", age: "20", Position: "developer" },
  { name: "Francis", age: "20", Position: "Software Engineer" }
];

const Users = () => {
  const [users, setUsers] = useState(initialUsers);

  return (
    <div>
      {users.map((user) => (
        <Useritems key={user.name} user={user} /> // don't forget the key, though will want to find something more unique than name!
      ))}
    </div>
  );
};

Upvotes: 1

Related Questions