Web Development · Module 9 · Lesson 41 min read

Lists, Keys & Forms

Rendering lists

React
<ul>
  {products.map((p) => (
    <li key={p.id}>{p.name}</li>
  ))}
</ul>
  • Every item needs a stable, unique key, usually the database id.
  • ⚠️ Don't use the array index as a key if items can be added, removed or reordered; React will mix up their state.

Controlled forms

The input's value lives in state, which makes validation and resetting easy:

React
const [email, setEmail] = useState("");
<input value={email} onChange={(e) => setEmail(e.target.value)} />

For several fields, keep one object:

React
const [form, setForm] = useState({ name: "", email: "" });
const update = (e) => setForm({ ...form, [e.target.name]: e.target.value });

Submitting

React
<form onSubmit={(e) => { e.preventDefault(); save(form); }}>

Derived values: don't store them in state

Calculate them during render instead:

React
const visible = products.filter((p) => p.name.toLowerCase().includes(query));

💡 For large forms, libraries like React Hook Form with Zod validation save a lot of code.

Example

JavaScript
import { useState } from "react";

export default function ProductSearch() {
  const [query, setQuery] = useState("");
  const [products, setProducts] = useState([
    { id: 1, name: "Laptop" }, { id: 2, name: "Mouse" }, { id: 3, name: "Monitor" },
  ]);
  const [newName, setNewName] = useState("");

  const visible = products.filter((p) =>
    p.name.toLowerCase().includes(query.toLowerCase()));   // derived, not stored

  const add = (e) => {
    e.preventDefault();
    if (!newName.trim()) return;
    setProducts([...products, { id: Date.now(), name: newName.trim() }]);
    setNewName("");
  };

  return (
    <div>
      <input placeholder="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
      <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
      <form onSubmit={add}>
        <input placeholder="New product" value={newName} onChange={(e) => setNewName(e.target.value)} />
        <button>Add</button>
      </form>
    </div>
  );
}
// 💻 Run in a Vite + React project