React Lists

  • React lists allow you to render a collection of elements dynamically.
  • They provide a way to map over an array and generate components based on its elements.

Rendering a Simple List

Using the map function to render a list of items.

import React from 'react';

const SimpleList = () => {
  const fruits = ['Apple', 'Banana', 'Orange'];

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

Rendering Lists of Components

Rendering a list of custom components using map.

import React from 'react';

const UserList = () => {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
  ];

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

Adding Keys to List Items

  • Providing a unique key to each list item helps React efficiently update the UI.

Conditional Rendering in Lists

Using conditional rendering within the map function.

import React from 'react';

const FilteredList = () => {
  const numbers = [1, 2, 3, 4, 5];

  return (
    <ul>
      {numbers.map((number) => (
        number % 2 === 0 && <li key={number}>{number}</li>
      ))}
    </ul>
  );
};

Handling List Events

Associating events with list items.

import React, { useState } from 'react';

const ClickableList = () => {
  const [selectedItem, setSelectedItem] = useState(null);
  const items = ['Item 1', 'Item 2', 'Item 3'];

  const handleItemClick = (item) => {
    setSelectedItem(item);
  };

  return (
    <ul>
      {items.map((item, index) => (
        <li
          key={index}
          onClick={() => handleItemClick(item)}
          className={selectedItem === item ? 'selected' : ''}
        >
          {item}
        </li>
      ))}
    </ul>
  );
};

 

Summary

Working with lists is a fundamental aspect of building dynamic and responsive React applications. Whether you're rendering a simple list or a list of components, mastering the use of map and keys ensures optimal performance and a seamless user experience.