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}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
HTMLButtonElementin the example above, it is a common mistake to useevent.targetinstead ofevent.currentTarget. The reason you want to useevent.currentTargetis thatevent.targetmay 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, andMouseEvent.
The event types that React provides and the DOM events they are related to are:
React.SyntheticEvent<T>for EventReact.AnimationEvent<T>for AnimationEventReact.CompositionEvent<T>for CompositionEventReact.InputEvent<T>for InputEventReact.UIEvent<T>for UIEventReact.FocusEvent<T>for FocusEventReact.KeyboardEvent<T>for KeyboardEventReact.MouseEvent<T>for MouseEventReact.PointerEvent<T>for PointerEventReact.DragEvent<T>for DragEventReact.WheelEvent<T>for WheelEventReact.TouchEvent<T>for TouchEventReact.ClipboardEvent<T>for ClipboardEventReact.TransitionEvent<T>for TransitionEvent
onChange handlers receive a React.ChangeEvent<T>.