React Lists Tutorial

This tutorial will teach React Lists in detail for beginners. Let's get starteed

What are React Lists?

  1. React lists are a powerful way to render multiple similar components from a collection of data.
  2. They are created using the map() function, which takes an array of data and returns an array of React elements.
const items = ["Item 1", "Item 2", "Item 3"];
    const itemList = items.map((item, index) => (
      <li key={index}>{item}</li>
    ));
    

Keyss

  1. Always provide a unique "key" prop to each item when rendering lists to optimize rendering and avoid warnings.
  2. Keys should be unique to each sibling element in the list, but they can be duplicated globally.
const items = ["Item 1", "Item 2", "Item 3"];
    const itemList = items.map((item, index) => (
      <li key={index}>{item}</li>
    ));

Adding State to List Items

  1. To add state (e.g., checkboxes) to list items, you should use a state management library like React's useState and useEffect.
import React, { useState, useEffect } from "react";

function Checklist() {
    const [items, setItems] = useState(["Item 1", "Item 2", "Item 3"]);

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

Handling List Events

  1. You can handle events on list items by attaching event handlers to them, such as click or hover events.
const items = ["Item 1", "Item 2", "Item 3"];

function handleItemClick(item) {
    alert(`Clicked: ${item}`);
}

const itemList = items.map((item, index) => (
    <li key={index} onClick={() => handleItemClick(item)}>
    {item}
</li>
));
    

Rendering Nested Lists

  1. To render nested lists, use a recursive component or nested mapping.
function NestedList({ items }) {
return (
    <ul>
    {items.map((item, index) => (
    <li key={index}>
        {item.name}
        {item.children && <NestedList items={item.children} />}
    </li>
    ))}
</ul>
);
}