Skip to main content

Lesson 2 of 8

Event Handlers - Typing Mouse, Keyboard & Form Events

React events are typed through generic synthetic event types. `React.ChangeEvent<T>`, `React.MouseEvent<T>`, `React.FormEvent<T>`, and `React.KeyboardEvent<T>` all carry the correct element type. Typing event handlers correctly prevents accessing properties that don't exist on the element.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Typed React Event Handlers

Typed React Event Handlers
// ── onChange - React.ChangeEvent ─────────────────────────────
interface SearchInputProps {
  value:    string;
  onChange: (value: string) => void;  // simplified - your handler signature
}

function SearchInput({ value, onChange }: SearchInputProps): React.ReactElement {
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    onChange(e.target.value);   // e.target.value is string ✅
  };

  return <input type="text" value={value} onChange={handleChange} />;
}

// ── Select change ─────────────────────────────────────────────
function PrioritySelect({ value, onChange }: {
  value:    Priority;
  onChange: (p: Priority) => void;
}): React.ReactElement {
  const handle = (e: React.ChangeEvent<HTMLSelectElement>): void => {
    // e.target.value is string - narrow to Priority before using:
    const p = e.target.value as Priority;
    // Better: validate with a type guard:
    if (["low","medium","high","critical"].includes(p)) {
      onChange(p);
    }
  };
  return (
    <select value={value} onChange={handle}>
      {(["low","medium","high","critical"] as Priority[]).map((p) => (
        <option key={p} value={p}>{p}</option>
      ))}
    </select>
  );
}

// ── onClick - React.MouseEvent ────────────────────────────────
function DeleteButton({ taskId, onDelete }: {
  taskId:   number;
  onDelete: (id: number) => void;
}): React.ReactElement {
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>): void => {
    e.stopPropagation();   // prevent event bubbling
    onDelete(taskId);
  };
  return <button onClick={handleClick} type="button">Delete</button>;
}

// ── onKeyDown - React.KeyboardEvent ──────────────────────────
function TaskInput({ onSubmit }: { onSubmit: (title: string) => void }): React.ReactElement {
  const [value, setValue] = React.useState("");

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      if (value.trim()) {
        onSubmit(value.trim());
        setValue("");
      }
    }
  };

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
      onKeyDown={handleKeyDown}
      placeholder="New task title..."
    />
  );
}

// ── Form submit - React.FormEvent ─────────────────────────────
function CreateTaskForm({ onCreate }: {
  onCreate: (input: Pick<Task, "title" | "priority">) => void;
}): React.ReactElement {
  const [title, setTitle]       = React.useState("");
  const [priority, setPriority] = React.useState<Priority>("medium");

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    if (!title.trim()) return;
    onCreate({ title: title.trim(), priority });
    setTitle("");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} required />
      <select value={priority} onChange={(e) => setPriority(e.target.value as Priority)}>
        <option value="low">Low</option>
        <option value="medium">Medium</option>
        <option value="high">High</option>
      </select>
      <button type="submit">Create Task</button>
    </form>
  );
}

Common Mistakes

  • Using `Event` instead of `React.ChangeEvent<HTMLInputElement>` - native DOM Event doesn't have `target.value`. Always use the React synthetic event types.
  • `e.target.value` is always `string` - even for `<input type='number'>`. Parse with `parseFloat` or `parseInt` before using as a number.
  • Forgetting `e.preventDefault()` on form submit - without it, the browser navigates on form submit, losing React state. Always call it in form submit handlers.

Tip

Tip

Practice Event Handlers Typing Mouse Keyboard Form Events in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Event Handlers - Typing Mouse, Keyboard & Form Events

Practice Task

Note

Practice Task - (1) Write a working example of Event Handlers Typing Mouse Keyboard Form Events from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Event Handlers Typing Mouse Keyboard Form Events is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • React events are typed through generic synthetic event types.
  • Using `Event` instead of `React.ChangeEvent<HTMLInputElement>` - native DOM Event doesn't have `target.value`. Always use the React synthetic event types.
  • `e.target.value` is always `string` - even for `<input type='number'>`. Parse with `parseFloat` or `parseInt` before using as a number.
  • Forgetting `e.preventDefault()` on form submit - without it, the browser navigates on form submit, losing React state. Always call it in form submit handlers.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done