Skip to main content

Event Handling

The React docs for handling events show how an event handler can be attached to a React element. To type these event handlers you may use React's event types, such as React.MouseEvent<T>, like this:

1import {useState} from 'react';2import * as React from 'react';3
4component MyComponent() {5  const [state, setState] = useState({count: 0});6
7  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {8    // To access your button instance use `event.currentTarget`.9    event.currentTarget as HTMLButtonElement;10
11    setState(prevState => ({12      count: prevState.count + 1,13    }));14  };15
16  return (17    <div>18      <p>Count: {state.count}</p>19      <button onClick={handleClick}>Increment</button>20    </div>21  );22}
Try

There are also other event types like React.KeyboardEvent<T>, React.ChangeEvent<T>, or React.TouchEvent<T>, all based on React.SyntheticEvent<T>. These event types typically take a single type argument: the type of the HTML element the event handler was placed on.

If you don't want to add the type of your element instance you can also use React.SyntheticEvent with no type arguments.

Note: To get the element instance, like HTMLButtonElement in the example above, it is a common mistake to use event.target instead of event.currentTarget. The reason you want to use event.currentTarget is that event.target may be the wrong element due to event propagation.

Note: React uses its own event system so it is important to use the React event types instead of the DOM types such as Event, KeyboardEvent, and MouseEvent.

The event types that React provides and the DOM events they are related to are:

onChange handlers receive a React.ChangeEvent<T>.

See Also​

  • Functions — event handlers are typed as function types
  • Generics — synthetic event types are generic over the DOM element type