In my ReactJS application I have been trying to solve this problem for a very long time.
In a Users.js file Im fetching all the users from the database and storing it in a state called user
. My goal is to render all these users by iterating through the list of users.
Here is my list of users that im getting from my backend:
Then I am running a loop in the Users.js
component and for every user, im rendering a User
component
Here is my Users.js
component:
import React, { useEffect, useState } from "react";
import User from "./User/User";
export default function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("http://localhost:8000/users")
.then((res) => {
console.log(res.data);
setUsers(res.data);
})
.catch((err) => console.log(err));
}, []);
return (
<div className="container">
{users.map((user) => {
console.log(user);
return <User key={user.id} username={user.username} />;
})}
</div>
);
}
here is my User.js
component:
import React from "react";
import { Link } from "react-router-dom";
export default function User(props) {
console.log("User.js component.");
console.log(props.username);
return (
<div>
<div className="card">
<Link to="/">
<div className="card-body">
Use this kinda element to show user: {props}
</div>
</Link>
</div>
</div>
);
}
I expected everything to run properly but I got this error:
I researched a little bit about the error and found out that it is because im passing an object as a prop to a component. But when I checked the typeof user.id
and typeof user.username
which i was passing as a prop to the User component. I found that none of them (user.id
and user.username
) were objects. They were number and string respectively.
Please help me solve this.
Thanks!