Utilizing Formik for Validation with Native Base Input Fields

I have incorporated Formik into my project to validate a native base input field using Yup schema. However, I am facing issues as the validation does not seem to be working correctly. Even when I enter alphabets, no errors are displayed.

The code functions properly (without Formik) as follows:

type EmailRegistrationProps = {};

interface FormValues {
  friendEmail: string;
}

type AddFriendEmailPageProps = {
  toggleShowPage: () => void;
  showAddFriendEmailPage: boolean;
};

export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
  toggleShowPage,
  showAddFriendEmailPage,
}) => {
  // Existing code without Formik
};

Now, I am attempting to integrate Formik:

EDIT:

export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
  toggleShowPage,
  showAddFriendEmailPage,
}) => {
  const initialValues: FormValues = {
    friendEmail: '',
  };

  // Code with Formik implementation
};

Although I want to continue using the existing handleSubmit function triggered by the button onPress event, I am encountering challenges in passing values and helpers for use within this function:

onPress={() => handleSubmit()}

An error message of Expected 2 arguments, but got 0 is displayed. On trying to pass values and helpers as arguments, I face "names not found" errors.

A similar issue arises at the end of the getFriendId function where I used [friendEmail, addFriend]. While this worked previously without Formik, it now fails due to unresolved references. I am struggling to seamlessly merge Formik functionality to reset values as was possible with useState.

Answer №1

To implement validation with Formik, you must use the <Field /> component.

The <Field /> component will automatically connect inputs to Formik and utilize the name attribute to correspond with Formik state. By default, <Field /> uses an HTML <input /> element.

You can specify custom components by using the component prop.

For instance, in your situation:

<Field
    component={Input}
    name="phoneNumber"
    placeholder="Phone Number"
    onChangeText={handleChange}
    onBlur={handleBlur}
    type='tel'
    value={values.phoneNumber}
/>

Update

I made a mistake earlier. I have corrected the onChangeText and onBlur functions to act accordingly. The current setup was triggering the "handle" events upon loading instead of when the event occurs. Simply naming the input should allow for automatic handling. Additionally, it is important to set a type for the input. The example above has been updated to include all these adjustments.

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

Utilizing jQuery to extract JSON data from various URLs and insert it into multiple div elements

I have an HTML list containing 4 items, each with its own assigned id. My goal is to retrieve JSON data from multiple URLs using AJAX for each item in the list and then parse the data into the respective item's id. Expected outcome: Each item receive ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

Avoid production build warnings in Vue.js without the need to build the code

Experimenting with vuejs, I decided to use it for a simple page even though I could have achieved the same without any framework. Now, my project is nearly production ready. The only issue is that it's just a single js and html file, but it shows thi ...

React modal image showing a misaligned image upon clicking

I recently integrated the react-modal-image library into my project to display images in a modal when clicked. However, I encountered an issue where the displayed image is off center with most of it appearing offscreen. I'm unsure what is causing this ...

What could be the reason for encountering the error "logic is not defined" in this particular

Having recently started learning JS and React, I encountered an error that stated: "logic is not defined". class Keyboard extends React.Component { logic() { return false; } render() { return ( <div> <h1>{log ...

Display the value on the screen based on the specified condition

Extracting the "address" value from the backend yields an uppercase result. To format it with only the first letters capitalized, I implemented a solution. However, an issue arises when the "address" value is missing. const capitalizeFirstLetter = (string) ...

When the button is clicked, two forms will be sent simultaneously and the PHP script will be

I have successfully set up my website with PayFast integration. Now, I need to run another PHP script when the user clicks on the place order button to save details in the database. Unfortunately, my code is quite long and I am not familiar with Ajax or Ja ...

When attempting to open a native app using JavaScript, it fails to function properly. However, the same code successfully opens the

These questions revolve around a web application developed in React that will be accessed through smartphones' browsers. I conduct testing on an iPhone using both Safari and Chrome. One of the steps involves opening a native authentication app. As pe ...

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

Leveraging Attr Jquery

I find myself in a perplexing situation My attempt to insert a button into a div with a specified width has hit a roadblock $('#main').append('<button id="hello" type="button" style="width:100px">Click Me!</button>'); Des ...

deciphering recursive collection of JSON objects in Angular

I'm currently working with an angular component that holds an array of nested JSON objects. My goal is to use a service to load these nested JSONs into separate objects within an array so I can easily look them up by their ID. I'm wondering if t ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Determining the correctness of a radio group tick pattern using jQuery

I am working on a form that has 3 questions with radio groups. The goal is to show a hidden div after all 3 radio boxes are checked. The condition for the div to appear is if the first question is answered "NO" and the remaining 2 questions are answered ...

Error: The function sendFile does not exist in the method res.status(...)

As a newcomer to this field, I must apologize if my issue has an obvious solution. However, I am encountering the following error: TypeError: res.status(...).sendFile is not a function at app.get (/root/discordtest/server.js:10:19) at callbacks (/ ...

Is it possible to showcase images on a webpage in real-time while it's being generated with the help of Flask and Python?

Trying to create a webpage that downloads media from my telegram account and displays it in real-time as images are downloaded one by one. Currently, all images are displayed at once after being downloaded, which is not the desired behavior. Now experiment ...

What is the process for importing the util module in Node.js?

I attempted to use the isDeepStrictEqual() method for object comparison but encountered this error: util.isDeepStrictEqual() is not a function After checking the official documentation, I found out that this method was introduced in Node.js v9.0.0 w ...

Leveraging a fetch request response in componentDidMount to power a subsequent request within a React-Redux component

I am currently facing a challenge with a component that triggers a fetch request (in redux) on componentDidMount. I now need to make another fetch request in the same component using the response data from the first fetch, and ideally before rendering. Si ...

It appears that you are currently utilizing legacy implementation in your code. To ensure optimal performance, we recommend updating your code by incorporating createWrapper() and wrapper.useWrappedStore()

I am encountering an issue while using redux toolkit with Next.js. I am receiving the following legacy warning- /!\ You are using a legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). I am unsure of whe ...

The find() function in JavaScript fails to identify duplicate values within an array of objects

I have created a bookmark feature with the following functionality: $scope.bookmarkPost = function(bookmark_post){ if(window.localStorage.bookmarks == null) { user_bookmarks = []; } else { user_bookmarks = JSON.parse(window.localStor ...

What is the best way to ensure that Jest waits for an event to occur before performing an assertion?

I've developed a facade for the nats streaming lib in the following way: import nats, { Message, Stan, Subscription, SubscriptionOptions } from 'node-nats-streaming' class NatsHelper { private client: Stan | null = null public connect( ...