Event Handling

The types and best practices for typing React event handlers with Flow

In the React docs “Handling Events” section a few different recommendations are provided on how to define event handlers. If you are using Flow we recommend that you use property initializer syntax as it is the easiest to statically type. Property initializer syntax looks like this:

1
2
3
class MyComponent extends React.Component<{}> {
  handleClick = event => { /* ... */ };
}

To type event handlers you may use the SyntheticEvent<T> types like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import * as React from 'react';

class MyComponent extends React.Component<{}, { count: number }> {
  handleClick = (event: SyntheticEvent<HTMLButtonElement>) => {
    // To access your button instance use `event.currentTarget`.
    (event.currentTarget: HTMLButtonElement);

    this.setState(prevState => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>
          Increment
        </button>
      </div>
    );
  }
}

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 use event.target instead of event.currentTarget. The reason why 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 SyntheticEvent types instead of the DOM types such as Event, KeyboardEvent, and MouseEvent.

The SyntheticEvent<T> types that React provides and the DOM events they are related to are:


Was this guide helpful? Let us know by sending a message to @flowtype.