0

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

2

1 Answer 1

1

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>
  );
};

Sign up to request clarification or add additional context in comments.

4 Comments

it is possible to achieve this without using hooks ?
No, you need to use hooks if you're using a functional component.
@James OP could just use a class component if he's using an older version of React (when hooks were not available yet) or if he just doesn't want to use them at this time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.