question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't figure out how to use this with Formik field component

See original GitHub issue

I’m using Formik and trying to use this package, but Formik can’t see the value of the input and thus doesn’t validate or submit the form.

Here’s the PhonInputField component that I’m using …

import PhoneInput from "react-phone-number-input";

const PhoneInputField = ({
    field,
    form
}) => {
    return (
        <div className="input-field">
            <PhoneInput
                placeholder="Enter phone number"
                name={field.name}
                value={field.value}
                onChange={field.onChange}
                onBlur={field.onBlur}
            />
        </div>
    );
};

export default PhoneInputField;

And here’s how I’m using it in Formik …

<Formik
    initialValues={initialValues}
    validationSchema={signInSchema}
    onSubmit={handleFormSubmit}
>
    {({
        isValid,
        isSubmitting,
        handleChange,
        handleBlur
    }) => (
        <Form>


                <Field
                    type="tel"
                    name="phone_number"
                    component={PhoneInputField}
                />

            <div className="cta">
                <button
                    type="submit"
                    disabled={!isValid || isSubmitting}
                    className="btn btn-primary big"
                >Submit</button>
            </div>
        </Form>
    )}
</Formik>

What am I doing wrong here?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:25 (10 by maintainers)

github_iconTop GitHub Comments

23reactions
AndrewStratigoscommented, Nov 23, 2019

If it helps, here is my phoneinput/formik control

import React, { useState } from 'react';
import PhoneInput from 'react-phone-number-input';
import PropTypes from 'prop-types';
import 'react-phone-number-input/style.css';
import { getIn } from 'formik';


const PhoneInputField = (props) => {
  const {
    className,
    field: { name, value },
    form: {
      errors, handleBlur, setFieldValue, touched,
    },
    form,
    label,
    country,
    onChange,
    disabled,
  } = props;

  const [isFocused, setFocused] = useState(false);
  const isError = getIn(touched, name) && getIn(errors, name);
  const errorStyle = isError ? 'error' : '';
  const filledStyle = (isFocused || value) ? 'filled' : '';
  const disabledStyle = disabled ? 'disabled' : '';

  const handleInputBlur = (e) => {
    setFocused(false);
    handleBlur(e);
  };

  const handleInputFocus = () => setFocused(true);

  const onValueChange = (phoneNumber) => {
    setFieldValue(name, phoneNumber);

    if (onChange !== null) {
      onChange(phoneNumber);
    }
  };

  return (
    <div className={`${className} ${errorStyle} ${filledStyle} ${disabledStyle} text-input-group`}>
      <PhoneInput
        placeholder="Enter phone number"
        name={name}
        value={value}
        onChange={onValueChange}
        country={country}
      />
      <label className="transition ml-10" htmlFor={name}>
        {label}
      </label>
      <div className="flex h-5 items-end text-red-100 text-xs">
        {isError && getIn(errors, name)}
      </div>
    </div>
  );
};

PhoneInputField.propTypes = {
  className: PropTypes.string,
  form: PropTypes.any.isRequired,
  field: PropTypes.any.isRequired,
  onChange: PropTypes.func,
  label: PropTypes.string,
  country: PropTypes.string,
  disabled: PropTypes.bool,
};

PhoneInputField.defaultProps = {
  className: '',
  label: '',
  onChange: null,
  country: 'AU',
  disabled: false,
};

export default PhoneInputField;
10reactions
MidhaTahircommented, Apr 28, 2021

In case if anyone needs help this is my current implementation. Below approach works with both onChange and onBlur events and doesn’t throw error when string is given in field (disabled). Thanks to above replies:

import "react-phone-number-input/style.css";
import PhoneInput from "react-phone-number-input";

const initialValues = {
    phoneNumber: "",
};

const validate = (values) => {
    let errors = {};
    if (!values.phoneNumber) {
      errors.phoneNumber = "⋆Required";
    }
    return errors;
  };

const onSubmit = (values, onSubmitProps) => {....}

  const formik = useFormik({
    initialValues,
    onSubmit,
    validate,
  });

<PhoneInput
          className='anonymous'
          placeholder='Phone Number'
          name='phoneNumber'
          value={formik.values.phoneNumber}
          onChange={e => formik.setFieldValue("phoneNumber", e)}
          onBlur={formik.handleBlur("phoneNumber")}
        />
        {formik.touched.phoneNumber && formik.errors.phoneNumber ? (
          <div
            className='text-danger text-right'
            style={{ marginBottom: "-13px", fontSize: "12px" }}
          >
            {formik.errors.phoneNumber}
          </div>
        ) : null}
Read more comments on GitHub >

github_iconTop Results From Across the Web

<Field /> | Formik
Formik will automagically inject onChange , onBlur , name , and value props of the field designated by the name prop to the...
Read more >
Formik Field not displaying entered value - Stack Overflow
This is the code snippet of my form, I have created a field and I want to change its value onChange. I don't...
Read more >
A guide to React forms and events using Formik
The Field component in Formik is used to automatically set up React forms with Formik. It's able to get the value by using...
Read more >
Formik Component in React - Pragim Tech
In rest of the cases, it is recommended to use Formik Component. One must remember that We cant use Form, field, Error Message...
Read more >
Using Formik to Handle Forms in React - CSS-Tricks
The <Formik/> component exposes various other components that adds more abstraction and sensible defaults. For example, components like <Form/ > ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found