Lists Rendering in React

In React, Rendering lists of items is a common task. To display multiple records at a time.

We can render lists using the "map()" function to iterate over an array of data and generate a set of components for each item.

Dynamic List Rendering in React:

Example:

import React from 'react';

const YourListComponent = () => {
  const list = ['Item 1', 'Item 2', 'Item 3'];

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

export default YourListComponent;
  • The items array contains the data we want to render in the list.

  • The `map()` function is used to iterate over the array.

  • For each item in the array, a new "li" element is created with the content of the item.

  • The key attribute is used to provide a unique identifier for each list item. This helps React efficiently update and re-render the list when the data changes.

Dynamic List Rendering with Child Components:

We can also render more complex components for each item in the list.

Example:

import React from 'react';

const YourListItem = ({ message, key }) => {
  return <li key={key}>{message}</li>;
};

const YourListComponent = () => {
  const list = [
    { id: 1, message: 'Item 1' },
    { id: 2, message: 'Item 2' },
    { id: 3, message: 'Item 3' },
  ];

  return (
    <ul>
      {list.map((item) => (
        <YourListItem key={item.id} message={item.message} />
      ))}
    </ul>
  );
};

export default YourListComponent;
  • The `items` array contains objects with `id` and `text` properties.

  • The `map()` function is used to iterate over the array.

  • For each `item` in the array, a new `ListItem` component is created with the key and text passed as props.

  • Providing key attributes on each root element on the list item helps to identify which items have changed, are added, or are removed, enabling efficient updates and re-renders.

Render list using Object.enteries() method:

Example:

import React from 'react';

const YourListItem = ({ attributeKey, value, key }) => {
  return <li key={key}>{attributeKey}: {value}</li>;
};

const YourListComponent = () => {
  const userDetails =  { 
	firstName: "alice",
	lastName: "collin",
	age: 24
   }


  return (
    <ul>
      {Object.entries(userDetails).map((item, index) => {
		console.log("key: ", item[0], "value: ", item[1])
		return (
        <YourListItem key={index} attributeKey={item[0]} value={item[1]} />
      )})}
    </ul>
  );
};

export default YourListComponent;
  • `Object.entries(yourObject)` method is used to iterate over objects `attributes` and `values`.

  • on Each loop iteration, it returns an array of ["key", "value"] associated with each other.

  • on index `0` of an array we will get `key` and on the index `1` of an array we will get `value`.

  • In the Next Step, we passed the `key` and `value` to the child component.