Typescript Formik typings in React Native for handling `handleSubmit` on `onPress`

Recently, I embarked on a project using React Native with Typescript and encountered Formik as my chosen tool for building forms within the application.

I found the informative tutorial guide by Formik to be very helpful, especially the section on using Formik with React Native in JavaScript.

However, when attempting to convert this example to typescript, I encountered a typing error related to the Button's onPress attribute:

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => 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>'.
          Types of property 'nativeEvent' are incompatible.
            Type 'NativeTouchEvent' is missing properties such as bubbles, cancelBubble, cancelable, composed, and more.
  Overload 2 of 2, '(props: ButtonProps, context?: any): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.ts(2769)
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAt...

After some investigation, it appears that the handleSubmit function

(e?: FormEvent<HTMLFormElement>) => void
, expects an event from a form submission (similar to the onSubmit attribute of a HTML form). Since React Native does not have a direct equivalent to a traditional form, it's raising an issue when receiving the input type
(ev: NativeSyntheticEvent<NativeTouchEvent>) => void
for the RN Button's onPress attribute.

To work around this error temporarily, I used the following approach, although I'm not entirely satisfied:

<Button
              title="Do it !"
              color={colors.red}
              onPress={
                (handleSubmit as unknown) as (
                  ev: NativeSyntheticEvent<NativeTouchEvent>
                ) => void
              }
/>

I am seeking advice on how to correctly resolve this typing error. Any guidance would be greatly appreciated!

CodeSandbox: App.tsx:32

Thank you for your assistance.

Answer №1

Your type can be defined as:

(event: GestureResponderEvent) => void;

Code snippet

Answer №2

Feel free to give this a shot

<Button 
onPress={e => handleSubmit(e as unknown as FormEvent<HTMLFormElement>)}
title="Submit"/>

Answer №3

My typical approach is:

<TouchableOpacity onPress={(event) => handleSubmitForm(event)}>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to verify the legitimacy of a union type of string literals during program execution

Looking for validation of a simple union type consisting of string literals to ensure its accuracy due to FFI calls to "regular" Javascript. Is there a method to confirm that a specific variable is an instance of any of these literal strings during runti ...

Is it permissible to incorporate a snackbar within my service?

I am trying to retrieve error details from a service call that communicates with an API in case of an error occurrence. For example, if the HTTP error returned is 422, I want to display a user-friendly message. Below is my service class: @Injectable() e ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route. ngOnInit() { if (!(this.route.snapshot.url[0].path ...

Expanding the range of colors in the palette leads to the error message: "Object is possibly 'undefined'. TS2532"

I am currently exploring the possibility of adding new custom colors to material-ui palette (I am aware that version 4.1 will include this feature, but it is a bit far off in the future). As I am relatively new to typescript, I am finding it challenging t ...

Create object properties as optional, declare them afterwards, and access them without needing to verify

I'm wondering if there's a way to work around type definitions. Let me provide an example to clarify my question. Suppose I want to define a type that consists of a large object containing multiple objects: type BigObject = { dom: HTMLElement, ...

Error encountered in react-test-renderer test due to TypeError: Attempting to access properties of an undefined variable, specifically trying to read the 'current

Having trouble with my unit tests using react-test-renderer. Even though the component I'm testing is working fine, the test won't pass. Can someone please help me figure out what I'm doing wrong? Below is the code for the component: // ...

"Learn how to dynamically update a value based on the selected option in a drop-down menu in Angular

Hello everyone. I am working on an angular project that includes a product page. Some products on this page can have multiple types, like so: Product ID-1 Type ID-1 Price-$10 Product ID-1 Type ID-2 Price-$15 Product ID-1 Type ID-3 Price-$25 In this sce ...

Issues with Typescript and TypeORM

QueryFailedError: SQLITE_ERROR: near "Jan": syntax error. I am completely baffled by this error message. I have followed the same steps as before, but now it seems to be suggesting that things are moving too slowly or there is some other issue at play. ...

What is the proper way to implement jest.mock in a describe or it block?

Using typescript and jest, I am faced with a scenario involving two files: users.service.ts, which imports producer.ts. In an attempt to mock a function in producer.ts, I successfully implement it. import { sendUserData } from "./users.service"; const pro ...

Information sent from TypeScript frontend to Java backend is converted into a LinkedHashMap

I have a situation where my typescript frontend is communicating with my java backend using REST. Recently, I added a new simple rest endpoint but encountered an issue when trying to cast the sent object properly because the body being sent is a LinkedHash ...

Issues arising from TypeScript error regarding the absence of a property on an object

Having a STEPS_CONFIG object that contains various steps with different properties, including defaultValues, I encountered an issue while trying to access the defaultValues property from the currentStep object in TypeScript. The error message indicated tha ...

Executing a function after another one has finished in Angular/TypeScript

I need to execute the f2 function only after the completion of f1, regardless of whether f1 is synchronous or asynchronous. To achieve this, I came up with a solution using a combination of Promise and a timer: executeFunctions() { this.f1().then(resu ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

Synchronization of data on mobile devices without the need

My current project involves developing a React Native application where the server side is up and running. To enable offline synchronization, I am considering integrating realm on the mobile device for handling offline data and syncing with the server wh ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

Is it possible to instruct TypeScript to add the ".js" extension to export/imports when using Node 16?

Is your TS 4.7 library configured to use ESM modules? Let's take a look at your tsconfig.json: "target": "ES2020", "module": ""ES2020", "lib": ["ES2020"], "moduleRe ...

What could be causing the error when my file is running?

Whenever I attempt to run a file using the command node database.ts, an error pops up. Can someone help me identify what's wrong with my syntax? This is how the file appears: import { Sequelize } from 'sequelize-typescript'; export const ...

An unexpected TypeScript error was encountered in the directory/node_modules/@antv/g6-core/lib/types/index.d.ts file at line 24, column 37. The expected type was

Upon attempting to launch the project post-cloning the repository from GitHub and installing dependencies using yarn install, I encountered an error. Updating react-scripts to the latest version and typescript to 4.1.2 did not resolve the issue. Node v: 1 ...

Choosing the primary camera on a web application with multiple rear cameras using WebRTC

Having a bit of trouble developing a web app that can capture images from the browser's back camera. The challenge lies in identifying which camera is the main one in a multi-camera setup. The issue we're running into is that each manufacturer u ...