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

Rendering Arrays of Objects is an important concept in React JS that allows developers to display structured data dynamically on a webpage. Applications commonly store information such as students, employees, products, orders, and users as arrays of objects. React uses JavaScript methods such as map() to transform these objects into JSX elements and display their properties in the user interface.

Learn React JS: JustAcademy React JS Training Course

Register for a demo: Register for React JS Course Demo


1. What Is an Array of Objects?

An array of objects is a JavaScript array that contains multiple objects. Each object stores related information as key-value pairs. This structure is useful when working with collections of similar records.

Example

const students = [
  { id: 1, name: "Rahul", age: 21, course: "React JS" },
  { id: 2, name: "Priya", age: 22, course: "JavaScript" },
  { id: 3, name: "Amit", age: 20, course: "HTML and CSS" }
];

In this example, students is an array containing three objects. Each object represents one student and includes an ID, name, age, and course.

Understanding the Structure

Term Meaning Example
Array A collection that stores multiple values. students
Object A collection of related properties. { name: "Rahul", age: 21 }
Property A named value inside an object. student.name
Index The position of an item in an array, starting at zero. students[0]

2. What Does Rendering Arrays of Objects Mean?

Rendering an array of objects means displaying information from each object as UI elements in a React component. Instead of manually creating JSX for every record, you can use the data to generate the elements dynamically.

For example, a student dashboard may need to display the names and courses of hundreds of students. By storing student records in an array, React can render the records using a reusable pattern.

Example Data

const products = [
  { id: 101, name: "Laptop", price: 55000 },
  { id: 102, name: "Keyboard", price: 1200 },
  { id: 103, name: "Mouse", price: 600 }
];

Each object represents a product. React can display the name and price of every product by iterating over the array.


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

  • Dynamic content: Display data based on the contents of an array.
  • Less repetitive code: Avoid writing separate JSX elements for every record.
  • Easy maintenance: Add, remove, or update records in the data instead of manually rewriting the UI.
  • Reusable components: Display each record using a common component structure.
  • API integration: Render data retrieved from a backend service.
  • Scalability: Use the same rendering logic for small or large collections.
  • Structured information: Display multiple properties, such as names, prices, categories, and statuses.

4. Using map() to Render an Array of Objects

The JavaScript map() method is commonly used to render arrays of objects in React. It processes each array item and returns a new array containing the results. In React, those results can be JSX elements.

Syntax

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

Example

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;

Output

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

Explanation

  1. The students array stores the student records.
  2. The map() method processes each student object.
  3. The student.name expression accesses the student's name.
  4. The student.course expression accesses the student's course.
  5. The key={student.id} attribute gives each rendered list item a stable identity.
  6. React renders the generated elements inside the unordered list.

5. Accessing Object Properties in JSX

To display information from an object, use dot notation or bracket notation inside JSX curly braces. Curly braces allow JavaScript expressions to be evaluated within JSX.

Using Dot Notation

const student = {
  id: 1,
  name: "Priya",
  age: 22
};

function StudentDetails() {
  return (
    <div>
      <h2>{student.name}</h2>
      <p>Age: {student.age}</p>
      <p>Student ID: {student.id}</p>
    </div>
  );
}

Using Bracket Notation

const student = {
  name: "Priya",
  age: 22
};

const propertyName = "name";

console.log(student[propertyName]);
// Output: Priya

Dot notation is commonly used when the property name is known in advance. Bracket notation is useful when the property name is stored in a variable or contains characters that cannot be used in dot notation.


6. Rendering Multiple Properties from Each Object

An object can contain several properties. You can display multiple properties from each record inside one JSX element or a group of elements.

Example

function EmployeeList() {
  const employees = [
    { id: 1, name: "Neha", role: "Developer", salary: 45000 },
    { id: 2, name: "Arjun", role: "Designer", salary: 40000 },
    { id: 3, name: "Sara", role: "Tester", salary: 38000 }
  ];

  return (
    <div>
      <h2>Employee Details</h2>
      {employees.map((employee) => (
        <div key={employee.id}>
          <h3>{employee.name}</h3>
          <p>Role: {employee.role}</p>
          <p>Salary: ₹{employee.salary}</p>
        </div>
      ))}
    </div>
  );
}

export default EmployeeList;

Here, React renders each employee's name, role, and salary. The employee ID is used as the key for the group of elements.


7. Rendering Arrays of Objects with Unique Keys

When rendering a collection, each sibling element should have a suitable key. A stable ID from the data is generally the best choice because it identifies the record rather than its position in the array.

Example

const books = [
  { id: "B101", title: "Learning React", author: "Alex" },
  { id: "B102", title: "JavaScript Basics", author: "Sam" },
  { id: "B103", title: "Web Development", author: "Riya" }
];

function BookList() {
  return (
    <ul>
      {books.map((book) => (
        <li key={book.id}>
          {book.title} by {book.author}
        </li>
      ))}
    </ul>
  );
}

Key Rules

  • Use a stable identifier such as book.id.
  • Keys should be unique among sibling elements.
  • Keep the key stable across renders for the same item.
  • Avoid generating random keys during rendering.
  • Avoid array indexes as keys for lists that can be reordered, inserted into, or deleted from.

Important: The key is for React's internal reconciliation process and is not passed to a component as a normal prop. Pass the ID separately if the component needs to read it.


8. Rendering Arrays of Objects Using Reusable Components

When the UI for each record becomes more complex, create a separate component for one item. The parent component can then use map() to render the reusable component for every object.

Example

function ProductCard({ product }) {
  return (
    <div>
      <h3>{product.name}</h3>
      <p>Price: ₹{product.price}</p>
      <p>Category: {product.category}</p>
    </div>
  );
}

function ProductList() {
  const products = [
    { id: 1, name: "Laptop", price: 55000, category: "Electronics" },
    { id: 2, name: "Keyboard", price: 1200, category: "Accessories" },
    { id: 3, name: "Mouse", price: 600, category: "Accessories" }
  ];

  return (
    <div>
      <h2>Product Catalog</h2>
      {products.map((product) => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
}

export default ProductList;

Advantages

  • Each component has a clear responsibility.
  • The same component can be reused with different data.
  • The parent component focuses on managing and rendering the collection.
  • The item component can be tested and maintained independently.

9. Rendering Arrays of Objects in a Table

Tables are useful when displaying structured records with several properties, such as employee information, product inventories, or student results.

Example

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

  return (
    <table border="1" cellPadding="8" cellSpacing="0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Course</th>
          <th>Marks</th>
        </tr>
      </thead>
      <tbody>
        {students.map((student) => (
          <tr key={student.id}>
            <td>{student.id}</td>
            <td>{student.name}</td>
            <td>{student.course}</td>
            <td>{student.marks}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

export default StudentTable;

Each student object becomes a table row. The student's ID is used as the key on the element returned by map().


10. Filtering Arrays of Objects Before Rendering

Sometimes an application needs to display only records that meet a condition. The JavaScript filter() method can select the required objects before map() converts them into JSX elements.

Example

function AvailableProducts() {
  const products = [
    { id: 1, name: "Laptop", available: true },
    { id: 2, name: "Tablet", available: false },
    { id: 3, name: "Phone", available: true }
  ];

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

The filter() method keeps only available products. Then, map() creates a list item for each remaining product.


11. Sorting Arrays of Objects Before Rendering

You can sort an array of objects before rendering it. Since JavaScript's sort() method mutates the array it operates on, copy the array first when you need to preserve the original data.

Example

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

  const sortedStudents = [...students].sort((a, b) =>
    a.name.localeCompare(b.name)
  );

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

The spread syntax [...students] creates a shallow copy of the array. The copy is sorted alphabetically by student name, while the original array remains unchanged.


12. Rendering Arrays of Objects from API Data

Many React applications fetch arrays of objects from a backend API. After retrieving the data and storing it in state, the application can use map() to display the records.

Example

import { useEffect, useState } from "react";

function UserList() {
  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("Unable 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>Error: {error}</p>;
  if (users.length === 0) return <p>No users found.</p>;

  return (
    <div>
      <h2>User List</h2>
      {users.map((user) => (
        <div key={user.id}>
          <h3>{user.name}</h3>
          <p>Email: {user.email}</p>
          <p>City: {user.address.city}</p>
        </div>
      ))}
    </div>
  );
}

export default UserList;

Explanation

  1. useState() stores the user array, loading status, and error message.
  2. useEffect() runs the fetching operation after the component mounts.
  3. fetch() requests data from the API.
  4. response.json() converts the response body into JavaScript data.
  5. setUsers(data) stores the array in state.
  6. map() renders each user object.
  7. Conditional checks handle loading, error, and empty states.

Note: This example requires an internet connection and an available API. In production, consider request cancellation, authentication, pagination, and other API-specific requirements as appropriate.


13. Handling Empty Arrays

An array may be empty because no records are available or because a search returned no results. A helpful interface should display a message instead of leaving the user confused.

Example

function MessageList() {
  const messages = [];

  return (
    <div>
      <h2>Messages</h2>
      {messages.length > 0 ? (
        <ul>
          {messages.map((message) => (
            <li key={message.id}>{message.text}</li>
          ))}
        </ul>
      ) : (
        <p>No messages available.</p>
      )}
    </div>
  );
}

The conditional expression checks the array length. If the array contains records, React renders the list; otherwise, it displays a message.


14. Handling Missing or Optional Object Properties

Not every object is guaranteed to contain every property. When a property is optional, use a fallback value or optional chaining where appropriate.

Example Using a Fallback

function UserCards() {
  const users = [
    { id: 1, name: "Rahul", city: "Mumbai" },
    { id: 2, name: "Priya" },
    { id: 3, name: "Amit", city: "Pune" }
  ];

  return (
    <div>
      {users.map((user) => (
        <div key={user.id}>
          <h3>{user.name}</h3>
          <p>City: {user.city || "Not provided"}</p>
        </div>
      ))}
    </div>
  );
}

Here, users without a city value display "Not provided". If empty strings should be treated differently from missing values, consider using nullish coalescing (??) instead of ||.


15. Common Mistakes When Rendering Arrays of Objects

Mistake Problem Solution
Forgetting key React may display a missing-key warning. Use a stable key such as item.id.
Using the wrong property name The expected value may be undefined. Check the object structure and property spelling.
Forgetting to return JSX A map callback with a block body may return undefined. Use an explicit return or an implicit return.
Calling map() on undefined The component may throw a runtime error. Initialize state with an array and validate API data.
Mutating the original array Direct mutation can cause confusing state-update behavior. Use immutable update patterns and copy arrays before sorting.
Using random keys Items may be recreated on every render. Use persistent IDs.
Assuming all properties exist Optional data may render incorrectly or cause errors when accessing nested values. Use suitable defaults and optional chaining.
Rendering too much data at once Very large lists can affect performance. Consider pagination or list virtualization.

16. Best Practices for Rendering Arrays of Objects

  • Use map() to convert array items into JSX elements.
  • Use stable, unique keys for sibling elements.
  • Access object properties using clear and consistent names.
  • Create reusable components when each record has a complex UI.
  • Handle loading, error, and empty states when working with API data.
  • Validate the shape of data received from external sources.
  • Avoid directly mutating state arrays.
  • Copy an array before using mutating methods such as sort() when the original should remain unchanged.
  • Use filter() and sort() to prepare data before rendering when necessary.
  • For large collections, consider pagination, virtualization, or other suitable performance strategies.

17. Difference Between Arrays of Objects and Arrays of Primitive Values

Feature Array of Primitive Values Array of Objects
Stored data Strings, numbers, booleans, and other primitive values. Objects containing multiple properties.
Example ["Apple", "Banana"] [{ id: 1, name: "Apple" }]
Accessing values Use the current value directly. Use properties such as item.name.
Typical use Simple lists of names or labels. Products, students, employees, users, and other structured records.
Rendering {items.map(item => ...)} {items.map(item => item.name)} or multiple properties.

18. Practical Project: Product Catalog

Build a simple product catalog that displays product names, prices, and categories from an array of objects.

Example Code

function ProductCatalog() {
  const products = [
    { id: 1, name: "Laptop", price: 55000, category: "Electronics" },
    { id: 2, name: "Keyboard", price: 1200, category: "Accessories" },
    { id: 3, name: "Headphones", price: 1800, category: "Audio" }
  ];

  return (
    <div>
      <h1>Product Catalog</h1>
      {products.map((product) => (
        <div key={product.id}>
          <h2>{product.name}</h2>
          <p>Price: ₹{product.price}</p>
          <p>Category: {product.category}</p>
        </div>
      ))}
    </div>
  );
}

export default ProductCatalog;

Project Learning Outcomes

  • Store structured product information in an array of objects.
  • Render each product dynamically with map().
  • Display multiple properties from every object.
  • Use unique keys for reliable list rendering.
  • Practice a common pattern used in shopping and inventory applications.

19. Interview Questions and Answers

Q1. What is an array of objects?

Answer: An array of objects is a collection in which each array item is an object containing related properties, such as an ID, name, and price.

Q2. How do you render an array of objects in React?

Answer: Use the map() method to iterate over the array and return JSX elements that display the required object properties.

Q3. Why is map() commonly used in React?

Answer: It returns a new array of values, making it suitable for transforming data arrays into arrays of JSX elements.

Q4. Why are keys needed when rendering objects?

Answer: Keys help React identify list items between renders. A stable unique ID is generally the preferred key.

Q5. Can we render multiple object properties?

Answer: Yes. Use expressions such as {item.name}, {item.price}, and {item.category} inside JSX.

Q6. How can we render only selected objects?

Answer: Use filter() to select matching objects and then use map() to render them.

Q7. How do you handle an empty array?

Answer: Check the array's length and display a message when no records are available.

Q8. How can React render data retrieved from an API?

Answer: Fetch the data, store the returned array in state, and use map() to render the records. Handle loading, error, and empty states as appropriate.

Q9. How do you avoid modifying an array while sorting?

Answer: Create a shallow copy using the spread syntax, such as [...items].sort(...), before sorting the array.

Q10. When should you create a reusable component for each object?

Answer: When the UI for an item contains multiple elements or complex logic, a reusable component can make the code easier to read, maintain, and test.


20. Practice Exercises

  1. Create an array of five student objects and display each student's name and course.
  2. Create a product catalog showing product names, prices, and categories.
  3. Build an employee directory displaying each employee's name, role, and department.
  4. Render an array of objects in an HTML table.
  5. Use filter() to display only products below a specified price.
  6. Sort student records alphabetically by name without modifying the original array.
  7. Fetch an array of users from an API and display their names and email addresses.
  8. Show a friendly message when the array contains no records.
  9. Create a reusable card component and use it to render an array of objects.
  10. Handle missing optional properties by displaying suitable fallback values.

21. Quick Revision Checklist

  • Understand the structure of an array of objects.
  • Know how to use map() to generate JSX.
  • Access object properties using dot or bracket notation.
  • Render multiple properties from each object.
  • Use stable keys for every rendered sibling item.
  • Understand how to use reusable components for complex list items.
  • Know how to render arrays in lists and tables.
  • Combine filter() and sort() with list rendering where needed.
  • Handle API loading, error, and empty states.
  • Avoid direct mutation of arrays used as React state.

22. Conclusion

Rendering Arrays of Objects is a fundamental React JS skill for building data-driven user interfaces. By combining arrays of structured data with the map() method, developers can display lists, cards, tables, product catalogs, student records, and API results without repeating JSX manually. Use stable keys, access object properties carefully, handle empty and optional data, and create reusable components for complex layouts.

Learn more through the JustAcademy React JS Training Course or register for a React JS course demo.

whatsapp