How to Render an Array of Objects in React? [in 3 easy steps]
Sep 06, 2024 7 Min Read 128600 Views
(Last Updated)
Do you have an array of objects or data items and want to list them in your React app? Well, you’re at the right place! Rendering an array of objects is pretty simple and this blog has been written to make it even more simpler for you.
In this blog, we’ll learn how to render an array of objects or data items in a react component with JSX and work on react map array of objects, keys in react, and how you can filter out data items with the help of JavaScript methods.
Rendering arrays of objects in React can be a challenge for developers who are new to the framework. Fortunately, React provides a powerful yet simple way of rendering data in an efficient manner. Let’s discuss this at length:
Table of contents
- What is an Array of Objects?
- Rendering an array of objects using JavaScript map()
- Steps to render an array of objects/list:
- Step 1: Create a react application
- Step 2: Changing the directory
- Step 3: Creating data as an array
- Step 4: Mapping the array into a new array of JSX nodes as arrayDataItems
- Step 5: Return arrayDataItems from the component wrapped in <ul>
- Complete Example:
- Output:
- Keys in React
- Example:
- Step 1: Creating data as an Array with Key
- Step 2: Mapping the array into a new array of JSX nodes as arrayDataItems
- Step 3: Return array Data Items from the component wrapped in <ul>
- Complete Example:
- Output:
- Filtering arrays of items
- Step 1: Create a new array having the category “Testing”
- Step 2: Mapping over “Testing”
- Step 3: Return arrayDataItems from the component wrapped in <ul>
- Complete Example:
- Output:
- Concluding Thoughts...
- How do you render multiple objects in React?
- How do I render multiple components?
- How to render an array of objects in React?
- How do you iterate an array of objects in React JS?
- How do you set an array of objects in state in React JS?
What is an Array of Objects?
An array of objects simply called a ‘List’ in React, is the collection of data having similar information. An array of objects can be anything like different data structures, car names, etc.
The most popular way to create a list or render an array of objects in React is using the array.map() method which takes an array of data and maps it to an array of components, so that each data item is represented by a corresponding component.
If you would like to explore React through a self-paced course, try GUVI’s React Self-paced certification course.
Additionally, the map() function can help with debugging and performance. This was just to give you a gist of what we’re about to discuss, let’s dive into the details now!
With the help of available JavaScript Array.map() and filter() methods, the array of objects/items can be transformed into an array of components also known as a list.
Lists are commonly used to store data retrieved from a server like any user information, etc. Each data object/item in the array consists of properties that can be easily accessed and manipulated.
For example, an array of objects in React could contain a list of car names, each of which has its own model and name. See the below syntax:
const carData = [
{
name: ‘BMW’,
model: 2022
},
{
name: Audi,
model: 2021
},
]
Given above is a list or array of objects consisting of names, and models of cars each of those having different properties.
We can use these arrays of objects to pass information between different components, store data in a state, or even populate lists in a component.
To render an array of objects/items in React, we have different ways such as: iterating a loop and using the map() and filter() functions. Out of all these methods, the most popular way is using Array.map().
Table of Contents
Also Read: How to use Props in React.
Rendering an array of objects using JavaScript map()
To render an array of objects/items in React, we loop through the array using the .map() method and return a single item.
In the below example, we loop through the courses array and return a <li> element for each item. We can use this method when we want to display a single element for each item in the given array.
When we call the .map() function in JavaScript it converts the array into whatever we return from the callback function we pass into it. This function always creates a new array. Let’s understand one example in detail, step by step.
Steps to render an array of objects/list:
Below are the steps needed to render an array of objects or lists in React:
Step 1: Create a react application
npx create-react-app demo
Step 2: Changing the directory
cd demo
Step 3: Creating data as an array
Once we have created a new react application, add the following code in the App.js file before the functional component App().
const courses = [
"Full Stack Developement Program",
"Python Automation Testing Program",
"UI/UX Program",
];
Step 4: Mapping the array into a new array of JSX nodes as arrayDataItems
const arrayDataItems = courses.map((course) => <li>{course}</li>);
Step 5: Return arrayDataItems from the component wrapped in <ul>
<ul>{arrayDataItems}</ul>
Complete Example:
App.js file
import "./App.css";
import React from "react";
//define the mock data
const courses = [
"Full Stack Developement Program",
"Python Automation Testing Program",
"UI/UX Program",
];
function App(props) {
/* Mapping the courses into a new array of JSX nodes as arrayDataItems */
const arrayDataItems = courses.map((course) => <li>{course}</li>);
return (
<div className="container">
<div>
<h1>Render List/Array of Items</h1>
</div>
{/* returning arrayDataItems wrapped in <ul> */}
<ul>{arrayDataItems}</ul>
</div>
);
}
export default App;
Output:
One thing that you may notice here is that the console will give you a warning such as the one below:
Warning: Each child in a list should have a unique “key” prop.
This warning states that we need to provide a unique key to each data item in the array. Next, we will examine why we want to add a unique key to a list of elements rendered by an array.
Keys in React
Keys in React help in knowing which array data item each component corresponds to. Also, Keys in React help in identifying and updating each item between renders without causing any bugs.
Rendering an array of items into a react component makes it important to always provide a key to track the items between renders. Generally, we use id: as the key in various data arrays.
Keys has some rules that we must follow to avoid any errors:
- Keys must be unique– every item of the array must have a unique key.
- Keys must be permanent– keys should not change their purpose or must not be changed between re-renders.
Example:
Let’s understand how we use keys in React to render an array of objects/lists. We must use keys in our data. For demonstrating this example, step1 and step2 will be the same.
Step 1: Creating data as an Array with Key
Once we have created a new react application, add the following code in the App.js file before the functional component App().
Earlier we hadn’t specified the unique key in the data but now have used them in our structured data to avoid warnings/errors.
const courses = [
{
id: 0,
name: 'Full Stack Developement Program',
price: '89,999'
},
{
id: 1,
name: 'Python Automation Testing Program',
price: '64,999'
},
{
id: 2,
name: 'UI/UX Program',
price: '89,999'
}
]
Step 2: Mapping the array into a new array of JSX nodes as arrayDataItems
const arrayDataItems = courses.map(course =>
<li key={course.id}>
<p>{course.name}</p>
<span>{course.price}</span>
</li>
)
Step 3: Return array Data Items from the component wrapped in <ul>
<ul>{arrayDataItems}</ul>
Complete Example:
App.js file
import "./App.css";
import React from "react";
//define the mock data with keys
const courses = [
{
id: 0,
name: 'Full Stack Developement Program',
price: '89,999'
},
{
id: 1,
name: 'Python Automation Testing Program',
price: '64,999'
},
{
id: 2,
name: 'UI/UX Program',
price: '89,999'
}
]
function App() {
/* Mapping the courses into a new array of JSX nodes as arrayDataItems */
const arrayDataItems = courses.map(course =>
<li key={course.id}>
<p>{course.name}</p>
<span>{course.price}</span>
</li>
)
return (
<div className="container">
<div>
<h1>Render List/Array of Items with Key</h1>
</div>
{/* returning arrayDataItems wrapped in <ul> */}
<ul>{arrayDataItems}</ul>
</div>
);
}
export default App;
App.css file (Optional)
.container {
margin-left: 20px;
}
.container h1 {
color: green
}
.container li {
display: flex;
flex-direction: column;
font-size: 20px;
background-color: #35F543;
width: 400px;
color: white;
padding: 2px;
border-radius: 20px;
justify-content: center;
align-items: center;
margin-bottom: 10px;
}
Output:
Filtering arrays of items
Till now we are returning a full array of items but what if we only want to show courses with a specific category? Then, we can use JavaScript’s filter() method to return just those with a matching category.
Filter() method takes an array of objects/items, passes and checks whether the function returns true or false, and finally returns a new array of filtered items that returned true. Let’s understand with the help of an example.
const courses = [
{
id: 0,
name: 'Full Stack Developement Program',
price: '89,999',
category: Software Development’
},
{
id: 1,
name: 'Python Automation Testing Program',
price: '64,999',
category: Testing’
},
{
id: 2,
name: 'UI/UX Program',
price: '89,999',
category: design’
}
]
In the above data, we have three different categories and let’s say we want only courses related to “Testing”, then the filter() method will return the course having a category as “Testing”.
Step 1: Create a new array having the category “Testing”
const testings = courses.filter(course =>
course.category === 'Testing’
);
Step 2: Mapping over “Testing”
const arrayDataItems = testings.map(course =>
<li key={course.id}>
<p>{course.name}</p>
<span>{course.price}</span>
<p>{course.category}</p>
</li>
)
Step 3: Return arrayDataItems from the component wrapped in <ul>
<ul>{arrayDataItems}</ul>
Complete Example:
App.js file
import "./App.css";
import React from "react";
//define the mock data with keys
const courses = [
{
id: 0,
name: 'Full Stack Developement Program',
price: '89,999',
category: 'Software Developmen',
},
{
id: 1,
name: 'Python Automation Testing Program',
price: '64,999',
category: 'Testing',
},
{
id: 2,
name: 'UI/UX Program',
price: '89,999',
category: 'design'
}
]
function App() {
/* new array of only 'testing' category */
const testings = courses.filter(course =>
course.category === 'Testing'
);
/* Mapping the courses into a new array of JSX nodes as arrayDataItems */
const arrayDataItems = testings.map(course =>
<li key={course.id}>
<p>{course.name}</p>
<span>{course.price}</span>
<p id="category">{course.category}</p>
</li>
)
return (
<div className="container">
<div>
<h1>Filtering List/Array of Items</h1>
</div>
{/* returning arrayDataItems wrapped in <ul> */}
<ul>{arrayDataItems}</ul>
</div>
);
}
export default App;
Wondering how you can code like this with ease? We’ve got the perfect learning resource: GUVI’s highly accredited Full Stack Development Bootcamp will turn you into a coding and development ninja in no time! Follow the link to learn more.
Output:
If you’re a React learner, must read the 6 Essential Prerequisites For Learning ReactJS.
Concluding Thoughts…
I hope this blog has helped you gain a much better understanding of rendering a list or array of objects in React. To render an array of objects, we saw how to use an array.map() function (and use react map array of objects).
Apart from this, we learned how to create an array of filtered items using JavaScript’s filter() method. We also noticed, that whilst rendering an element inside the component, we must use a unique key to avoid any errors.
Regardless of which method we use, it is important to remember that we need to access the data within the object to render it correctly.
How do you render multiple objects in React?
You can use the Array’s map functionality to render multiple elements in React. Simply map all your objects into React fragments, so that your Function component can make use of it. But don’t forget to set a unique key prop!
How do I render multiple components?
Even if we have multiple elements to render, there can only be a single root element. This means that if we want to render two or more elements, we have to wrap them in another element or component. Commonly, the element used for this is a <div> tag.
How to render an array of objects in React?
Using these simple and easy steps, you can render an array of objects in React:
Step 1: Create a react application.
Step 2: Change directory.
Step 3: Create data as an array.
Step 4: Mapping the array into a new array of JSX nodes as arrayDataItems.
Step 5: Return arrayDataItems from the component wrapped in <ul>
How do you iterate an array of objects in React JS?
To iterate through an array of objects in ReactJS, you must use the mao() method. It creates a new array by applying a provided function to each element of the original array. Within the function, you can access and render each object’s properties as and when needed, effectively iterating through and rendering them in your React component.
How do you set an array of objects in state in React JS?
To set an array of objects in the state of a React component, you can use the ‘useState’ hook. So to do this, first, import ‘useState’ from ‘react’. Then, declare a state variable using useState and initialize it with your array of objects. To update the state, use the setter function provided by the useState hook. And voila, now you can easily manage and modify the array of objects within your component’s state.
Great! I enjoyed reading about the map() method used in React.