TypeScript Course
TypeScript
/
Intermediate

React: Typing Events

Definition

Providing accurate types for Event Objects passed to event handler functions (like `onClick` or `onChange`) in React.

Explain Like I'm New

In vanilla JS, an event is just an `Event`. In React, events are wrapped in a 'SyntheticEvent'. If you have an `onChange` handler for an input, you must type the event so TypeScript knows it is allowed to read `event.target.value`.

Real World Example

An input handler: `const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setValue(e.target.value); }`.

Common Use Cases

  • •Form handling
  • •Button clicks
  • •Keyboard navigation

Interactive Example

import React, { useState } from 'react';

export function LoginForm() {
  const [text, setText] = useState("");

  // 1. Typing a Form Input Change Event
  // Requires specifying WHICH HTML element triggered the change
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
  };

  // 2. Typing a Form Submit Event
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log("Submitted:", text);
  };

  // 3. Typing a Mouse Event
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    console.log("Clicked at X:", e.clientX);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={text} onChange={handleChange} />
      <button onClick={handleClick} type="submit">Login</button>
    </form>
  );
}

Interview Questions

basic

  • Do you need to type the event if the function is written completely inline?

intermediate

  • What is the event type for an `<input>` onChange handler?

advanced

  • What is the difference between `React.MouseEvent` and `MouseEvent`?

Flash Cards

Question

Do you need to type inline events?

Click to reveal answer
Answer

No! If you write `<button onClick={(e) => console.log(e)}>`, TS uses Contextual Typing to perfectly infer the event type automatically. You only need explicit event types when defining the handler function outside of the JSX.

Question

React.MouseEvent vs MouseEvent?

Click to reveal answer
Answer

`MouseEvent` is the native DOM event type. `React.MouseEvent` is React's cross-browser wrapper (SyntheticEvent). You must use the React versions when working inside React components.