It is important to append unique keys when rendering a list of objects in React.js. That way, React would know ahead of time whether or not to update a particular item in the list (if the corresponding state changes). Here I’m going to show how you can display a list of items (objects) in React.js:
Here’s my App.js file:
import "./styles.css";
import UsersList from "./UserList";
import usersData from "./usersData";
export default function App() {
return (
<div className="App">
<UsersList users={usersData} />
</div>
);
}
Code language: JavaScript (javascript)
In the above file, I’ve imported usersData which essentially contains a list of data like name, email, id. I’ve also imported UsersList component which takes in the usersData and renders the required list. So, here’s the usersData.js file:
const usersData = [
{
id: 1,
name: "Shruti",
age: 25,
email: "shruti@example.com"
},
{
id: 2,
name: "John",
age: 24,
email: "john@example.com"
},
{
id: 3,
name: "Jack",
age: 30,
email: "jack@example.com"
},
{
id: 4,
name: "Jenny",
age: 26,
email: "jenny@example.com"
}
];
export default usersData;
Code language: JavaScript (javascript)
And here’s the UsersList.js component which creates multiple instances of the User component and passes in each of the object of the usersData list as follows:
import User from "./User";
const UsersList = ({ users }) => {
return (
<section>
{users.map((user, index) => {
return <User key={user.id} {...user}></User>;
})}
</section>
);
};
export default UsersList;
Code language: JavaScript (javascript)
And finally here’s the User.js component:
const User = ({ name, age, email }) => {
return (
<article className="list-container">
<h2>
{name} ({age})
</h2>
<h3>{email}</h3>
</article>
);
};
export default User;
Code language: JavaScript (javascript)
Given, everything works correctly, you should see the following view on the screen:
Links: Codesandbox / Demo | Github