dagda1
dagda1

Reputation: 28770

What type to give flow annotations for onChange etc

I have the following component:

import { identity } from 'lodash';

export const Input = ({
  onChange = identity
  //etc.
}: {
  onChange: Event<HTMLInputElement>,
}) => <Input onChange={onChange} />

But when I run flow I get this error:

onChange = identity,
       ^^^^^^^^^^^^^^^^^^^ default value. Expected polymorphic type instead of
onChange = identity,
       ^^^^^^^^ class type: Event

I'm confused as to where to find the definition for Event.

If I look at facebook's dom types:

I can see Event here which has a target property of type EventTarget.

But looking at the EventTarget definition, I don't see any definiton for value.

I don't see to define the synthetic event so that it has a target of type HtmlInputElement.

Upvotes: 11

Views: 6618

Answers (5)

Vladislav Kosovskikh
Vladislav Kosovskikh

Reputation: 476

onChange event might look like this (notice using currentTarget instead of target):

onChange = (e: SyntheticInputEvent<HTMLInputElement>): void => {
    this.setState({ value: e.currentTarget.value });
}

Upvotes: 2

Estev&#227;o Lucas
Estev&#227;o Lucas

Reputation: 4678

For React Native:

import { type SyntheticEvent } from "react-native/Libraries/Types/CoreEventTypes";
type TextInputEvent = SyntheticEvent<{ value: string }>;

Than you can just use it: onChange: (TextInputEvent) =>

Upvotes: 1

Emily Maskin
Emily Maskin

Reputation: 304

As TLadd said, SyntheticInputEvent is what you want for the parameter. However it requires a type argument, so you'll need to make it SyntheticInputEvent<HTMLInputElement>.

Upvotes: 15

TheTFo
TheTFo

Reputation: 811

I would take a look at the flow doc:

https://flow.org/en/docs/frameworks/react/#adding-types-for-react-events-a-classtoc-idtoc-adding-types-for-react-events-hreftoc-adding-types-for-react-eventsa

You'd want something like this:

class MyComponent extends React.Component {
  onChange(event: Event & { currentTarget: HTMLInputElement }) {
    // ...
  }
}

Upvotes: 7

TLadd
TLadd

Reputation: 6884

Flow has built in definitions for synthetic events. The one you would want in this case is SyntheticInputEvent (https://github.com/facebook/flow/blob/v0.49.1/lib/react.js#L310)

So the type of onChange would be

{ 
   onChange: (SyntheticInputEvent) => mixed,
}

A function that takes in a SyntheticInputEvent and returns a mixed time, which basically just means that you don't care what the function returns (if anything).

Upvotes: 3

Related Questions