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 the SyntheticEvent<T>
types like this:
1import {useState} from 'react';2import * as React from 'react';3
4function MyComponent(): React.Node {5 const [state, setState] = useState({count: 0}); 6
7 const handleClick = (event: SyntheticEvent<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}
5:29-5:48: Cannot call hook [1] because React hooks can only be called within components or hooks. [react-rule-hook]
There are also more specific synthetic event types like
SyntheticKeyboardEvent<T>
, SyntheticMouseEvent<T>
, or
SyntheticTouchEvent<T>
. The SyntheticEvent<T>
types all 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
SyntheticEvent
with no type arguments like so: SyntheticEvent<>
.
Note: To get the element instance, like
HTMLButtonElement
in the example above, it is a common mistake to useevent.target
instead ofevent.currentTarget
. The reason you want to useevent.currentTarget
is thatevent.target
may be the wrong element due to event propagation.
Note: React uses its own event system so it is important to use the
SyntheticEvent
types instead of the DOM types such asEvent
,KeyboardEvent
, andMouseEvent
.
The SyntheticEvent<T>
types that React provides and the DOM events they are
related to are:
SyntheticEvent<T>
for EventSyntheticAnimationEvent<T>
for AnimationEventSyntheticCompositionEvent<T>
for CompositionEventSyntheticInputEvent<T>
for InputEventSyntheticUIEvent<T>
for UIEventSyntheticFocusEvent<T>
for FocusEventSyntheticKeyboardEvent<T>
for KeyboardEventSyntheticMouseEvent<T>
for MouseEventSyntheticDragEvent<T>
for DragEventSyntheticWheelEvent<T>
for WheelEventSyntheticTouchEvent<T>
for TouchEventSyntheticTransitionEvent<T>
for TransitionEvent