# React Event Handlers

> Synthetic events vs Native events.

Subject: TypeScript | Lesson 53 of 54 | 3 min read
Interactive lesson: https://codewithanimation.in/typescript/react-event-handlers
Previous: [React Hooks Typing](https://codewithanimation.in/typescript/react-hooks-typing.md) | Next: [The satisfies Operator](https://codewithanimation.in/typescript/satisfies-operator.md)

## The Synthetic Wrapper

When you click a button in React, the `event` object you receive in `onClick` is *not* a native browser DOM event.

React intercepts all native events and wraps them in a cross-browser `SyntheticEvent`. Because of this, TypeScript requires you to use React's specific event types, like `React.MouseEvent`.

## The Mismatch Error

If you try to type a React click handler as `e: MouseEvent` (the native DOM type), TypeScript will yell at you. The props expect `React.MouseEvent<HTMLButtonElement>`.

This distinction is crucial when you are mixing vanilla DOM event listeners with React event handlers.

## Syntax

```tsx
import React from "react";

// ❌ Wrong: Native DOM Event
function handleClick(e: MouseEvent) { }

// ✅ Right: React Synthetic Event + Element Generic
function handleClick(e: React.MouseEvent<HTMLButtonElement>) { }

export function Button() {
  return <button onClick={handleClick}>Click Me</button>
}
```

## Common mistake: The Form Submit Trap

The most commonly mis-typed event is form submission. It is *not* a `MouseEvent` or an `InputEvent`. It is `React.FormEvent<HTMLFormElement>`.

## Tip: Contextual Typing

If you define your handler *inline* inside the JSX, TypeScript will automatically infer the event type for you! `onClick={(e) => console.log(e)}`. You only need manual types when defining the function outside the component.

## Try it: Try it

Observe the difference between typing a native browser event listener and typing a React component's event handler.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/react-event-handlers

## Check yourself

### Question 1

Why does React use `React.MouseEvent` instead of the browser's native `MouseEvent`?

- A. React events are faster than native events.
- B. React wraps native events in a 'SyntheticEvent' to ensure they behave identically across all web browsers.
- C. Native events cannot be typed in TypeScript.

Correct answer: B

React's SyntheticEvent system normalizes events so that they have the same properties across different browsers (Chrome, Safari, Firefox). Therefore, you must use React's types for React events.

## Remember this

- React uses Synthetic Events, not Native DOM events.
- Type click events as `React.MouseEvent<HTMLElement>`.
- Type form submissions as `React.FormEvent<HTMLFormElement>`.
- Inline handlers (`onClick={(e) => ...}`) are auto-typed by TypeScript.
