React-phone-input-2 with Formik return empty string in values return

51 Views Asked by At

I want to link Formik with React-Phone-Input-2 in the phone field, it does not allow me to use HandleChange, HandleBlur and values.phone is returned with empty string on submit

How can i handle it ?

import { useFormik } from "formik";
import React, { useState } from "react";
import * as Yup from "yup";
import axios from "axios";
import PhoneInput from "react-phone-input-2";

const validationSchema = Yup.object({
    phone: Yup.string().required("Phone number is required").matches("^.{10,}$", "Phone number must be not less than 10 numbers"),
});

    const userData = {
        phone: "",
    };

    const { values, handleSubmit, handleChange, handleBlur, errors, touched } = useFormik({
        initialValues: userData,
        onSubmit,
        // validate,
        validationSchema,
    });

    return (
        <>
            <div className="w-75 mx-auto p-lg-5 mb-5">
                <h2 className="text-center">Register Now</h2>
                <form action="" className="form-register p-4 rounded-3" onSubmit={handleSubmit}>

                    <label htmlFor="phone">Phone Number: </label>
                    <PhoneInput
                        value={values.phone}
                        onChange={() => handleChange}
                        onBlur={handleBlur}
                        country={"eg"}
                        inputProps={{
                            id: "phone",
                        }}
                        countryCodeEditable={false}
                        enableSearch={true}
                        // id="phone"
                        className=" mb-3"
                        placeholder="Enter Your Phone Number"
                    />
                    {errors.phone && touched.phone && <p className="alert alert-danger fs-6 p-1">{errors.phone}</p>}

                    <div className="d-flex justify-content-end">
                        <button type="submit" className="btn bg-main p-2 text-white rounded-3">
                            Register
                        </button>
                    </div>
                </form>
            </div>
        </>
    );
}

I want to return values.phone as a value not an empty string

1

There are 1 best solutions below

1
inno1304d On
<Formik
    initialValues={initialValues}
    validationSchema={validationSchema}
    onSubmit={onSubmit}
>
    {formik => (
        <Form>
            <PhoneInput
                country={"in"}
                value={formik.values.phone}
                onChange={value => formik.setFieldValue("phone", value)}
                onBlur={formik.handleBlur}
                placeholder="Enter your Number"
                inputClass="field_input1"
            />
        </Form>
    )}
</Formik>



try this