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. Under the current configuration, we only infer component-syntax components to be components and hook-syntax hooks to be hooks. (https://react.dev/reference/rules/rules-of-hooks) [react-rule-hook]7:31-7:44: Cannot resolve name `SyntheticEvent`. [cannot-resolve-name]7:46-7:62: Cannot resolve name `HTMLButtonElement`. [cannot-resolve-name]9:28-9:44: Cannot resolve name `HTMLButtonElement`. [cannot-resolve-name]
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
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
SyntheticEventtypes 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