6

In the Formik documentation for React Native it has an example form:

<Formik initialValues={{ email: '' }} onSubmit={(values) => console.log(values)}>
  {({ handleChange, handleBlur, handleSubmit, values }) => (
    <View>
      <TextInput onChangeText={handleChange('email')} onBlur={handleBlur('email')} value={values.email} />
      <Button onPress={handleSubmit} title="Submit" />
    </View>
  )}
</Formik>

This, however, gives me a Typescript error:

No overload matches this call.
Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
  Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.
    Types of parameters 'e' and 'ev' are incompatible.
      Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.

Given that I am getting the handleSubmit function from destructuring, how can I cast the type of event correctly?

Note: I know I can do this, but I have read that this will cause additional renders in React:

<Button onPress={(e) => handleSubmit(e as any)} title="Submit" />
mahi-man
  • 4,326
  • 2
  • 25
  • 36
  • "but I have read that this will cause additional renders in React" can you explain this? – Vencovsky Jul 27 '20 at 11:34
  • Where the component `Button` comes from? – Vencovsky Jul 27 '20 at 11:36
  • Button comes from react native: `import { Button, TextInput } from 'react-native';` – mahi-man Jul 27 '20 at 20:08
  • Regarding re-renders, see here for an explanation: https://stackoverflow.com/a/36677798/4553162 – mahi-man Jul 27 '20 at 20:09
  • About your explanation, it depends if you are using functional or class component – Vencovsky Jul 28 '20 at 10:55
  • On reading a bit more, I think in this case using an inline arrow function is ok. I.e. I'll stick to this: ` – mahi-man Jul 28 '20 at 20:19
  • 1
    https://github.com/formium/formik/issues/376/ It seems that this error is know for quite some time. To avoid rerenders and not get errors you can try: onPress={handleSubmit as any} This is not ideal, but it will prevent unnecessary rerenders. – Jan Jaworski Aug 14 '20 at 10:07

2 Answers2

4

Maybe it's not the best but you can do something like this

  <Button
     onPress={handleSubmit as (values: any) => void} // <= add this
     title="Submit" />
Mina Makar
  • 71
  • 1
  • 5
0

Based on the Mina Makar's answer I resolved the type error the following way:

<Button
  onPress={
    handleSubmit as (values:
      GestureResponderEvent |
      React.FormEvent<HTMLFormElement> |
      undefined) => void
  }
/>
ivts
  • 111
  • 6