Popular Searches
Popular Course Categories
Popular Courses

Rendering Arrays of Objects

Rendering Arrays of Objects

Lists and Dynamic Rendering

Rendering Arrays of Objects in React JS

Topic: Rendering Arrays of Objects in React JS

Rendering arrays of objects is an important React concept used to display dynamic collections of data such as student records, product lists, employee details, blog posts, orders, and user profiles. React commonly uses JavaScript's map() method to convert each object in an array into JSX elements.


1. What Is Rendering an Array of Objects?

Rendering an array of objects means displaying data stored in an array as visible elements in a React component. Each object represents one record and contains properties such as id, name, age, price, or category.

For example, an array may contain three student objects. React can display each student's name, course, and marks in a list of cards or rows.

Example of an Array of Objects

const students = [
  { id: 1, name: "Rahul", course: "React JS", marks: 85 },
  { id: 2, name: "Priya", course: "JavaScript", marks: 92 },
  { id: 3, name: "Amit", course: "HTML and CSS", marks: 78 }
];

In this example, students is an array containing three objects. Every object stores information about one student.


2. Why Do We Render Arrays of Objects in React?

  • Display dynamic data: Show information received from APIs or databases.
  • Reduce repetitive code: Avoid writing the same JSX structure for every record.
  • Improve maintainability: Update the array instead of manually changing many JSX elements.
  • Create reusable interfaces: Display products, employees, students, or articles using a common layout.
  • Support changing data: Render new records when data is added, removed, or updated.
  • Build real-world applications: Create dashboards, e-commerce pages, task managers, and admin panels.

3. Understanding the map() Method

The JavaScript map() method creates a new array by calling a function for every item in an existing array. In React, that function commonly returns JSX for each object.

Syntax

array.map((item) => {
  return (
    <div key={item.id}>
      {item.property}
    </div>
  );
});

Important Parts

  • array: The collection of data to process.
  • map(): Iterates over the array and creates a new array of results.
  • item: Represents the current array element.
  • item.id: Accesses a property of the current object.
  • key={item.id}: Provides React with a stable identifier for the rendered element.
  • return: Returns the JSX for each item when using a block body.

4. Basic Example: Rendering an Array of Objects

In this example, React displays student names and courses using map().

import React from "react";

function StudentList() {
  const students = [
    { id: 1, name: "Rahul", course: "React JS" },
    { id: 2, name: "Priya", course: "JavaScript" },
    { id: 3, name: "Amit", course: "HTML and CSS" }
  ];

  return (
    <div>
      <h2>Student List</h2>
      <ul>
        {students.map((student) => (
          <li key={student.id}>
            {student.name} - {student.course}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default StudentList;

Expected Output

Student List
Rahul - React JS
Priya - JavaScript
Amit - HTML and CSS

Explanation: The map() method processes each student object. The JSX accesses each object's name and course properties. React renders each result as an <li> element.


5. Accessing Object Properties in JSX

To display information from an object, use dot notation inside JSX curly braces.

const employee = {
  id: 101,
  name: "Neha",
  role: "Frontend Developer",
  salary: 45000
};

return (
  <div>
    <h2>{employee.name}</h2>
    <p>Role: {employee.role}</p>
    <p>Salary: ₹{employee.salary}</p>
  </div>
);

When rendering an array of these objects, use the current item variable, such as employee.name, inside the map() callback.

Example with Multiple Properties

const employees = [
  { id: 1, name: "Neha", role: "Developer", city: "Mumbai" },
  { id: 2, name: "Karan", role: "Designer", city: "Pune" },
  { id: 3, name: "Meera", role: "Tester", city: "Nashik" }
];

function EmployeeList() {
  return (
    <div>
      <h2>Employee Directory</h2>
      {employees.map((employee) => (
        <div key={employee.id}>
          <h3>{employee.name}</h3>
          <p>Role: {employee.role}</p>
          <p>City: {employee.city}</p>
        </div>
      ))}
    </div>
  );
}

6. Rendering Arrays of Objects as Cards

Arrays of objects are often displayed as cards rather than plain lists. Each card can show a record's name, description, price, and other details.

import React from "react";

function ProductList() {
  const products = [
    { id: 101, name: "Laptop", price: 55000, category: "Electronics" },
    { id: 102, name: "Headphones", price: 2500, category: "Accessories" },
    { id: 103, name: "Keyboard", price: 1800, category: "Accessories" }
  ];

  return (
    <div>
      <h2>Our Products</h2>
      <div className="product-list">
        {products.map((product) => (
          <div className="product-card" key={product.id}>
            <h3>{product.name}</h3>
            <p>Category: {product.category}</p>
            <p>Price: ₹{product.price}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

export default ProductList;

Optional CSS

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.product-card {
  width: 220px;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #fff;
}
.product-card h3 {
  margin-top: 0;
}

Result: Each product appears in its own card, with the product name, category, and price.


7. Using Destructuring While Rendering Objects

JavaScript destructuring allows you to extract properties from an object into variables. It can make JSX cleaner when several properties are needed.

Without Destructuring

{students.map((student) => (
  <div key={student.id}>
    <h3>{student.name}</h3>
    <p>{student.course}</p>
    <p>{student.marks}</p>
  </div>
))}

With Destructuring

{students.map(({ id, name, course, marks }) => (
  <div key={id}>
    <h3>{name}</h3>
    <p>Course: {course}</p>
    <p>Marks: {marks}</p>
  </div>
))}

Both examples produce the same kind of output. Destructuring is optional, so choose the style that makes your code easiest to read.


8. Rendering Nested Arrays of Objects

An object may contain another array. For example, a department can contain a list of employees, or a category can contain multiple products. In such cases, use a nested map().

const departments = [
  {
    id: 1,
    name: "Development",
    employees: [
      { id: 11, name: "Rahul" },
      { id: 12, name: "Priya" }
    ]
  },
  {
    id: 2,
    name: "Design",
    employees: [
      { id: 21, name: "Amit" },
      { id: 22, name: "Neha" }
    ]
  }
];

function DepartmentList() {
  return (
    <div>
      {departments.map((department) => (
        <section key={department.id}>
          <h2>{department.name}</h2>
          <ul>
            {department.employees.map((employee) => (
              <li key={employee.id}>{employee.name}</li>
            ))}
          </ul>
        </section>
      ))}
    </div>
  );
}

Explanation: The outer map() renders each department. The inner map() renders employees within that department. Each rendered list uses its own stable key.


9. Rendering Objects Received Through Props

A parent component can pass an array of objects to a child component through props. This makes the child reusable with different data sets.

Parent Component

function App() {
  const courses = [
    { id: 1, title: "React JS", duration: "8 Weeks" },
    { id: 2, title: "JavaScript", duration: "6 Weeks" }
  ];

  return <CourseList courses={courses} />;
}

Child Component

function CourseList({ courses }) {
  return (
    <div>
      <h2>Available Courses</h2>
      {courses.map((course) => (
        <div key={course.id}>
          <h3>{course.title}</h3>
          <p>Duration: {course.duration}</p>
        </div>
      ))}
    </div>
  );
}

The parent owns the data in this example, while the child receives it and displays it. The child does not need to create a duplicate array.


10. Rendering Arrays of Objects from API Data

Real-world React applications frequently retrieve arrays of objects from APIs. The data may be loaded asynchronously, so a component should account for loading, errors, and empty results.

Example Using useEffect and useState

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function fetchUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );

        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    }

    fetchUsers();
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p role="alert">Error: {error}</p>;
  }

  if (users.length === 0) {
    return <p>No users found.</p>;
  }

  return (
    <div>
      <h2>Users</h2>
      {users.map((user) => (
        <div key={user.id}>
          <h3>{user.name}</h3>
          <p>Email: {user.email}</p>
          <p>City: {user.address?.city || "Not available"}</p>
        </div>
      ))}
    </div>
  );
}

export default Users;

How it works:

  1. useState() stores the users, loading status, and error message.
  2. useEffect() starts the API request when the component mounts.
  3. fetch() requests the data, and response.json() parses it.
  4. setUsers(data) updates the state with the returned array.
  5. React re-renders the component and displays the user objects using map().
  6. Loading, error, and empty states help the interface handle different situations.

Important: This example expects the API to return an array of user objects. Always verify the API's response structure before rendering it.


11. Filtering Arrays of Objects Before Rendering

The filter() method selects objects that satisfy a condition. You can combine it with map() to display only matching records.

const students = [
  { id: 1, name: "Rahul", marks: 85 },
  { id: 2, name: "Priya", marks: 92 },
  { id: 3, name: "Amit", marks: 48 },
  { id: 4, name: "Neha", marks: 76 }
];

function PassedStudents() {
  const passedStudents = students.filter(
    (student) => student.marks >= 50
  );

  return (
    <div>
      <h2>Passed Students</h2>
      {passedStudents.map((student) => (
        <p key={student.id}>
          {student.name}: {student.marks}
        </p>
      ))}
    </div>
  );
}

In this example, only students with marks of 50 or more are rendered.


12. Sorting Arrays of Objects Before Rendering

The sort() method orders array items. Because sort() modifies the original array, use a copy when the original data should remain unchanged.

const products = [
  { id: 1, name: "Keyboard", price: 1800 },
  { id: 2, name: "Laptop", price: 55000 },
  { id: 3, name: "Mouse", price: 700 }
];

function SortedProducts() {
  const sortedProducts = [...products].sort(
    (a, b) => a.price - b.price
  );

  return (
    <div>
      {sortedProducts.map((product) => (
        <p key={product.id}>
          {product.name}: ₹{product.price}
        </p>
      ))}
    </div>
  );
}

The spread operator ([...products]) creates a shallow copy before sorting. The displayed products are ordered from lowest to highest price.


13. Searching Arrays of Objects

A search feature can filter an array of objects according to user input. The following example uses a controlled input to search student names.

import { useState } from "react";

function StudentSearch() {
  const [search, setSearch] = useState("");

  const students = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Priya" },
    { id: 3, name: "Amit" }
  ];

  const filteredStudents = students.filter((student) =>
    student.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <h2>Search Students</h2>
      <input
        type="text"
        value={search}
        onChange={(event) => setSearch(event.target.value)}
        placeholder="Enter student name"
      />
      {filteredStudents.length > 0 ? (
        filteredStudents.map((student) => (
          <p key={student.id}>{student.name}</p>
        ))
      ) : (
        <p>No matching students found.</p>
      )}
    </div>
  );
}

export default StudentSearch;

Whenever the input changes, React updates the search state and renders the matching student objects.


14. Rendering Arrays of Objects with Conditional Content

You can use conditions inside a mapped element to display different information depending on an object's properties.

const orders = [
  { id: 1, product: "Laptop", status: "Delivered" },
  { id: 2, product: "Headphones", status: "Pending" },
  { id: 3, product: "Keyboard", status: "Delivered" }
];

function OrderList() {
  return (
    <div>
      {orders.map((order) => (
        <div key={order.id}>
          <h3>{order.product}</h3>
          {order.status === "Delivered" ? (
            <p>Your order has been delivered.</p>
          ) : (
            <p>Your order is being processed.</p>
          )}
        </div>
      ))}
    </div>
  );
}

This pattern is useful for order tracking, task status, account states, and product availability.


15. Understanding Keys When Rendering Objects

A key is a special React attribute that helps React identify which items in a rendered collection have changed, been added, or been removed.

Correct Example

{products.map((product) => (
  <div key={product.id}>
    {product.name}
  </div>
))}

Incorrect Example

{products.map((product) => (
  <div>{product.name}</div>
))}

The second example omits a key and may produce a React warning. Use a stable, unique identifier from the data whenever possible.

Key Rules

  • Keys should be unique among sibling elements in the same list.
  • Prefer stable IDs such as database IDs or unique record IDs.
  • Avoid generating random keys during rendering.
  • Avoid array indexes when the list can be reordered, inserted into, or deleted from.
  • Place the key on the outermost element returned for each item.
  • The key attribute is for React's internal reconciliation and is not passed to the component as a normal prop.

16. Handling Empty Arrays

If an array contains no objects, calling map() produces an empty array, so no list items appear. It is often better to display a helpful message.

function ProductList({ products }) {
  if (products.length === 0) {
    return <p>No products available.</p>;
  }

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

This component expects products to be an array. If the prop can be missing or null, provide a default value or validate it before reading length.

Using a Default Prop Value

function ProductList({ products = [] }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

17. Common Mistakes and Their Solutions

Mistake Why It Is a Problem Solution
Forgetting key React may show a missing-key warning. Use a stable ID such as key={item.id}.
Using the wrong property The expected value may be undefined. Check the object structure and property names.
Using forEach() to return JSX forEach() returns undefined, not a mapped array. Use map() to create JSX elements.
Mutating an array with sort() The original array is changed. Sort a copy using [...items].sort(...).
Rendering before API data is ready The data may initially be empty or unavailable. Handle loading and error states and initialize state appropriately.
Using array indexes as keys for changing lists Items can be matched incorrectly after changes. Prefer stable, unique identifiers.
Not handling an empty array The page can appear blank. Display an empty-state message.
Assuming API data is always an array The response may have a different structure. Inspect and validate the response before mapping.
Using item.key without a data property The intended key may be undefined. Use the actual unique property, such as item.id.

18. map() vs forEach() in React

Feature map() forEach()
Returns a new array Yes No
Commonly used to render JSX Yes No
Transforms every item Yes Executes a callback for every item
Suitable for JSX expressions Yes Not directly
Example items.map(item => <p key={item.id}>{item.name}</p>) items.forEach(item => console.log(item.name))

19. Reusable Component for Rendering Object Arrays

For larger applications, create a reusable component that receives an array of objects through props. The parent can provide different data while the component handles the common display structure.

function ItemList({ items }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          <strong>{item.name}</strong>
          {item.description && (
            <p>{item.description}</p>
          )}
        </li>
      ))}
    </ul>
  );
}

export default ItemList;

You can reuse ItemList for different collections as long as the objects contain the expected properties and a stable unique id.


20. Mini Project: Student Management List

Project objective: Create a student list that displays student details, searches by name, and filters students by passing marks.

Complete Example

import { useState } from "react";

function StudentManager() {
  const [search, setSearch] = useState("");
  const [showPassedOnly, setShowPassedOnly] = useState(false);

  const students = [
    { id: 1, name: "Rahul Sharma", course: "React JS", marks: 85 },
    { id: 2, name: "Priya Verma", course: "JavaScript", marks: 92 },
    { id: 3, name: "Amit Kumar", course: "HTML and CSS", marks: 42 },
    { id: 4, name: "Neha Singh", course: "React JS", marks: 76 }
  ];

  const filteredStudents = students.filter((student) => {
    const matchesSearch = student.name
      .toLowerCase()
      .includes(search.toLowerCase());

    const matchesMarks = !showPassedOnly || student.marks >= 50;

    return matchesSearch && matchesMarks;
  });

  return (
    <div>
      <h1>Student Management</h1>
      <input
        type="text"
        value={search}
        onChange={(event) => setSearch(event.target.value)}
        placeholder="Search students"
      />
      <label>
        <input
          type="checkbox"
          checked={showPassedOnly}
          onChange={(event) => setShowPassedOnly(event.target.checked)}
        />
        Show passed students only
      </label>
      {filteredStudents.length === 0 ? (
        <p>No students match your search.</p>
      ) : (
        filteredStudents.map((student) => (
          <div key={student.id}>
            <h3>{student.name}</h3>
            <p>Course: {student.course}</p>
            <p>Marks: {student.marks}</p>
            <p>Status: {student.marks >= 50 ? "Passed" : "Failed"}</p>
          </div>
        ))
      )}
    </div>
  );
}

export default StudentManager;

Project Features

  • Stores student details in an array of objects.
  • Uses map() to render student records.
  • Uses filter() for name searching and pass-status filtering.
  • Uses controlled inputs and React state.
  • Uses stable student IDs as keys.
  • Displays a message when no matching records are found.

Suggested Improvements

  1. Add a new student through a form.
  2. Add a delete button to remove a student.
  3. Add sorting by marks or student name.
  4. Move the student array into state if the list needs to change dynamically.
  5. Load student data from an API.

21. Interview Questions and Answers

Q1. What does rendering an array of objects mean in React?

Answer: It means converting each object in an array into JSX elements so that the object's data can be displayed in the user interface.

Q2. Which JavaScript method is commonly used to render arrays in React?

Answer: The map() method is commonly used because it returns a new array containing the JSX elements generated for each item.

Q3. Why do we use keys when rendering arrays?

Answer: Keys help React identify list items between renders so it can handle additions, removals, and changes correctly.

Q4. Can we render object properties directly in JSX?

Answer: Yes. Use curly braces, such as {'{student.name}'}, to display a property value inside JSX.

Q5. What is the difference between map() and filter()?

Answer: map() transforms each item into a new result, while filter() selects only items that satisfy a condition. They are often combined when displaying filtered data.

Q6. Why should we avoid random keys?

Answer: Random keys change between renders, preventing React from reliably matching existing list items and potentially causing unnecessary remounts.

Q7. Can we render nested arrays of objects?

Answer: Yes. Use nested map() calls and provide stable keys for each rendered list item.

Q8. How do you handle an empty array?

Answer: Check the array's length and display a message such as “No records found” when it contains no items.

Q9. How can API data be rendered in React?

Answer: Fetch the data, parse the response, store the array in state, and use map() to render the records. Handle loading, errors, and empty results.

Q10. Does map() modify the original array?

Answer: No. map() returns a new array. However, if the callback mutates objects inside the array, those object mutations can still affect the original data.

Q11. What happens if the key is missing?

Answer: React commonly shows a warning about missing keys for elements rendered in a list. Supply a stable key for each sibling item.

Q12. Should we use array indexes as keys?

Answer: Prefer stable IDs. Indexes may be acceptable for static lists that never change order or have items inserted or removed, but can cause problems for dynamic lists.


22. Practice Exercises

  1. Create an array of five employee objects and display their names and job titles.
  2. Create a product list with names, prices, and categories.
  3. Render a list of courses and their durations.
  4. Display only students whose marks are greater than or equal to 60.
  5. Sort products from highest to lowest price without modifying the original array.
  6. Create a search field that filters employee names.
  7. Render departments with nested employee arrays.
  8. Fetch a list of users from an API and display loading and error messages.
  9. Show an empty-state message when no search results are found.
  10. Build a student management component with search, filtering, and stable keys.

23. Best Practices

  • Use map() to transform arrays into JSX.
  • Use meaningful variable names such as student, product, or employee.
  • Access object properties using the correct property names.
  • Use stable and unique keys for sibling elements.
  • Keep components small and reusable.
  • Use filter() for filtering and sort a copy when preserving the original array matters.
  • Handle empty data, loading states, and API errors.
  • Validate API response structures before rendering.
  • Avoid mutating React state directly.
  • Use destructuring when it improves readability.
  • Keep data transformation logic clear and separate from complex JSX when appropriate.

24. Quick Revision Checklist

  • Understand what an array of objects is.
  • Know how the JavaScript map() method works.
  • Access object properties inside JSX with curly braces.
  • Render lists using stable, unique keys.
  • Use destructuring to simplify property access.
  • Render nested arrays with nested map() calls.
  • Pass arrays of objects through props.
  • Render data retrieved from APIs.
  • Combine filter(), sort(), and map() when needed.
  • Handle loading, errors, and empty arrays.
  • Build a reusable component for displaying records.

25. Conclusion

Rendering arrays of objects is a fundamental React skill for creating dynamic and data-driven interfaces. The map() method transforms each object into JSX, while object properties provide the values displayed to users. By combining map() with stable keys, props, state, filtering, sorting, and API requests, you can build reusable components for real-world applications such as student management systems, product catalogs, employee directories, and dashboards.

Practice these examples and gradually move from simple lists to API-driven projects to strengthen your React JS skills.


26. React JS Training and Course Demo

Learn more about React JS concepts, components, rendering, props, state, and practical application development through the following resources:

Previous Next
whatsapp