viclafouch / mui-tel-input

📌 A phone number input designed for MUI (Material ui) V6 built with libphonenumber-js
https://viclafouch.github.io/mui-tel-input
MIT License
171 stars 66 forks source link

[Enhancement] add wrapper for React Final Form #61

Closed BennyAlex closed 1 year ago

BennyAlex commented 1 year ago

Hello,

I had some problems integrating the phone input into RFF but got it working now.

Here is my code, maybe we can have it as a integration into this package itself or add it to the docs:


import { MuiTelInput, matchIsValidTel } from 'mui-tel-input';
import { Field } from 'react-final-form';

function showErrorOnChange({
  meta: { submitError, dirtySinceLastSubmit, error, touched, modified }
}) {
  return !!(
    ((submitError && !dirtySinceLastSubmit) || error) &&
    (touched || modified)
  );
}

function PhoneWrapper(props) {
  const {
    input: { name, value, onChange, onBlur, onFocus, ...restInput },
    meta,
    required,
    fullWidth = true,
    helperText,
    showError = showErrorOnChange,
    ...rest
  } = props;

  const { error, submitError } = meta;
  const isError = showError({ meta });

  return (
    <MuiTelInput
      fullWidth={fullWidth}
      helperText={isError ? error || submitError : helperText}
      error={isError}
      onChange={onChange}
      onBlur={onBlur}
      onFocus={onFocus}
      name={name}
      value={value}
      required={required}
      inputProps={{ required, ...restInput }}
      {...rest}
    />
  );
}

function PhoneInput(props) {
  const { name, fieldProps, ...rest } = props;

  return (
    <Field
      validate={(value) => {
        if (value && matchIsValidTel(value)) {
          return undefined;
        } else {
          return 'Enter valid phone number';
        }
      }}
      name={name}
      render={({ input, meta }) => (
        <PhoneWrapper input={input} meta={meta} name={name} {...rest} />
      )}
      {...fieldProps}
    />
  );
}

export default PhoneInput;

And when using a form it can easily used by

<PhoneInput
              label='Phone'
              name='phone'
              required
              defaultCountry='DE'
            />
viclafouch commented 1 year ago

Hello !

No need integration into the package itself. I will add a section into the doc ;)