Monday, 18 November 2024

How to Iterate Over Arrays in React Components?

To iterate over an array in React components, you typically use JavaScript's array methods like map(), forEach(), or loops like for and while. The most common and preferred method in React is map() because it returns a new array, which you can directly use to render JSX (React’s syntax).

Syntax 1: Using Curly Braces {} with Explicit Return

array.map((item, index) => {
  // logic for each item in the array
});

 

The curly braces {} indicate that this is the function body, so you can write multiple lines of code or more complex logic. : Inside the curly braces, you must explicitly use the return keyword to return the value (such as JSX).

 

Example

array.map((item, index) => {
  // Multiple lines of logic can go here
  console.log(item);  // some other logic
  return <li key={index}>{item}</li>;
});

In this case, the function is expected to return the JSX <li key={index}>{item}</li>, but it needs the return statement because you're using curly braces.

 

Syntax 2: Using Parentheses () with Implicit Return

array.map((item, index) => (
  // logic for each item in the array
));

When you use parentheses () after the arrow function, you don't need to write the return keyword. JavaScript automatically returns the result of the expression inside the parentheses. This works well when your function logic is short and only involves a single statement (like rendering JSX).

 

Example

array.map((item, index) => (
  <li key={index}>{item}</li>
));

Here, the JSX <li key={index}>{item}</li> is implicitly returned without needing the return keyword.

 

Both approaches are correct and can be used depending on the complexity of the logic inside the function.

 

Example 1: Simple List Rendering


export default function ItemsList() {
  const items = ['Apple', 'Banana', 'Cherry'];

  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

When rendering lists, each element must have a unique key prop. This helps React to identify which items have changed, added, or removed and optimizes rendering. In this case, we used the index as the key. While using index works, it's better to use unique IDs when possible.

 

Example 2: Rendering a List of Objects

export default function EmployeeList() {
  const employees = [
    { id: 1, name: 'Ram', role: 'Manager' },
    { id: 2, name: 'Robert', role: 'Developer' },
    { id: 3, name: 'Rahim', role: 'Designer' }
  ];

  return (
    <ul>
      {employees.map((employee) => (
        <li key={employee.id}>
          {employee.name} - {employee.role}
        </li>
      ))}
    </ul>
  );
}

Follow step-by-step procedure to build a complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘iterate-over-arrays’.

 

Project structure looks like below.




Step 2: Create components folder in src/ folder and define EmployeeDetails component.

 

EmployeeDetails.jsx

export default function EmployeeDetails() {
  let employees = [
    { id: 1, name: "Krishna", age: 34, hobbies: ["Playing Cricket", "Hockey"] },
    { id: 2, name: "Ram", age: 35 },
    { id: 3, name: "Chamu", age: 32, hobbies: ["Trekking", "Cooking"] },
    { id: 4, name: "Sailu", age: 36, hobbies: ["Reading", "Dancing"] },
  ];

  return (
    <div>
      <h1>Employee Details</h1>
      <table>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Hobbies</th>
          </tr>
        </thead>

        <tbody>
          {employees.map((emp) => {
            return (
              <tr key={emp.id}>
                <td>{emp.id}</td>
                <td>{emp.name}</td>
                <td>{emp.age}</td>
                <td>
                  <ul>
                    {emp.hobbies &&
                      emp.hobbies.map((hobby) => (
                        <li key={`${emp.id}-${hobby}`}>{hobby}</li>
                      ))}
                  </ul>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

Step 3: Update main.jsx file like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import EmployeeDetails from './components/EmployeeDetails'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <EmployeeDetails />
  </StrictMode>,
)

Step 4: Build and run the application.

cd iterate-over-arrays
npm install
npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.



You can download this Application from this link.

 

Using forEach loop

import React from 'react';

function ItemList() {
  const items = ['Apple', 'Banana', 'Cherry'];
  let itemList = [];

  items.forEach((item, index) => {
    itemList.push(<li key={index}>{item}</li>);
  });

  return <ul>{itemList}</ul>;
}

export default ItemList;

 

Using for loop

import React from 'react';

function ItemList() {
  const items = ['Apple', 'Banana', 'Cherry'];
  let itemList = [];

  for (let i = 0; i < items.length; i++) {
    itemList.push(<li key={i}>{items[i]}</li>);
  }

  return <ul>{itemList}</ul>;
}

export default ItemList;

 

Let’s create two more components, one using for-each loop and other using for loop.

 

EmployeeDetailsForEachLoop.jsx

export default function EmployeeDetailsForEachLoop() {
  let employees = [
    { id: 1, name: "Krishna", age: 34, hobbies: ["Playing Cricket", "Hockey"] },
    { id: 2, name: "Ram", age: 35 },
    { id: 3, name: "Chamu", age: 32, hobbies: ["Trekking", "Cooking"] },
    { id: 4, name: "Sailu", age: 36, hobbies: ["Reading", "Dancing"] },
  ];

  let itemList = [];

  employees.forEach((emp) => {
    itemList.push(
      <tr key={emp.id}>
        <td>{emp.id}</td>
        <td>{emp.name}</td>
        <td>{emp.age}</td>
        <td>
          <ul>
            {emp.hobbies &&
              emp.hobbies.map((hobby) => (
                <li key={`${emp.id}-${hobby}`}>{hobby}</li>
              ))}
          </ul>
        </td>
      </tr>
    );
  });

  return (
    <div>
      <h1>Employee Details Using for-each loop</h1>
      <table>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Hobbies</th>
          </tr>
        </thead>

        <tbody>{itemList}</tbody>
      </table>
    </div>
  );
}

EmployeeDetailsUsingForLoop.jsx

export default function EmployeeDetailsUsingForLoop() {
  let employees = [
    { id: 1, name: "Krishna", age: 34, hobbies: ["Playing Cricket", "Hockey"] },
    { id: 2, name: "Ram", age: 35 },
    { id: 3, name: "Chamu", age: 32, hobbies: ["Trekking", "Cooking"] },
    { id: 4, name: "Sailu", age: 36, hobbies: ["Reading", "Dancing"] },
  ];

  let itemList = [];

  for (let i = 0; i < employees.length; i++) {
    let emp = employees[i];
    itemList.push(
      <tr key={emp.id}>
        <td>{emp.id}</td>
        <td>{emp.name}</td>
        <td>{emp.age}</td>
        <td>
          <ul>
            {emp.hobbies &&
              emp.hobbies.map((hobby) => (
                <li key={`${emp.id}-${hobby}`}>{hobby}</li>
              ))}
          </ul>
        </td>
      </tr>
    );
  }
  return (
    <div>
      <h1>Employee Details Using for loop</h1>
      <table>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Hobbies</th>
          </tr>
        </thead>

        <tbody>{itemList}</tbody>
      </table>
    </div>
  );
}

Update main.jsx like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import EmployeeDetails from './components/EmployeeDetails'
import EmployeeDetailsUsingForLoop from './components/EmployeeDetailsUsingForLoop'
import EmployeeDetailsForEachLoop from './components/EmployeeDetailsUsingForEachLoop'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <EmployeeDetails />
    <EmployeeDetailsUsingForLoop />
    <EmployeeDetailsForEachLoop />
  </StrictMode>,
)

Final screen looks like below.



You can download this application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment