Ryan H.
Ryan H.

Reputation: 7844

How should an onChange event be annotated in an exported React Component?

I have a React Component with an onChange handler:

// @flow
import React, {Component} from 'react';

export default class MyList extends Component {
  handleChange = (event) => {
    // Do something with event.target.value
    // which will be the value typed in the input field.
  }

  render() {
    return (
      <input type="text" onChange={this.handleChange}> />
    );
  }
}

and Flow complains about this because it is an exported class: Parameter `event` missing annotation

How can I annotate the event parameter in the handleChange function? As far as I know, this event is generated at the JavaScript level and doesn't have any Flow typing.

Alternatively, can Flow be configured to not display these "missing annotation" errors?

Upvotes: 3

Views: 4665

Answers (2)

Gianluca Casati
Gianluca Casati

Reputation: 3753

I found another solution, using synthetic events: something like the following

onChange (event: SyntheticInputEvent<EventTarget>): void {
  this.setState({ text: event.target.value })
}

Upvotes: 5

gcanti
gcanti

Reputation: 1462

You can find the typings here https://github.com/facebook/flow/blob/master/lib/dom.js

handleChange = (event: Event) => {
  if (event.target instanceof HTMLInputElement) {
    console.log(event.target.value)
  }
}

Upvotes: 4

Related Questions