Skip to content
React

Event Handling and List Rendering

Handle events and render dynamic lists with keys in React.

By EZ4Code Team
eventlistintermediate

Code

import { useState } from "react";

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState("");

  const add = () => {
    if (!text.trim()) return;
    setTodos([...todos, { id: Date.now(), text, done: false }]);
    setText("");
  };

  const toggle = (id) => {
    setTodos(todos.map((t) =>
      t.id === id ? { ...t, done: !t.done } : t
    ));
  };

  const remove = (id) => {
    setTodos(todos.filter((t) => t.id !== id));
  };

  return (
    <div>
      <input
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => e.key === "Enter" && add()}
      />
      <button onClick={add}>Add</button>
      <ul>
        {todos.map((t) => (
          <li key={t.id}>
            <span
              style={{ textDecoration: t.done ? "line-through" : "none" }}
              onClick={() => toggle(t.id)}
            >
              {t.text}
            </span>
            <button onClick={() => remove(t.id)}>x</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Explanation

Manages a todo list with add, toggle, and remove operations using immutable state updates (spread, map, filter). Each list item uses a stable key (Date.now()) so React can efficiently reconcile additions and removals. Event handlers like onKeyDown enable Enter-to-add keyboard interaction.

More React Snippets