Use Input Mask with Material UI component

1.8k Views Asked by At

I want to use Input Mask with material-ui component.

I am using

"react": "^17.0.2" "yup": "^0.32.9" "@mui/material": "^5.0.0" "react-imask": "^6.4.0"

The problem is that The phone number gets cleared when I click the submit button.


const TextMaskCustom = forwardRef(
  function TextMaskCustom(props, ref) {
    const { onChange, name, ...rest } = props;

    return (
      <IMaskInput
        mask="000-000-0000"
        definitions={{ "#": /[1-9]/ }}
        inputRef={ref}
        onAccept={(value) => onChange({ target: { name: name, value } })}
        overwrite
        {...rest }
      />
    );
  }
);

export default function App() {
  const schema = Yup.object().shape({
    phoneNumber: Yup.string().required("Required!")
  });

  const {
    register,
    formState: { errors },
    handleSubmit
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = ({phoneNumber}) => {
    console.log(phoneNumber);
  };

  return (
     ...
      <Input
        name="cpf"
        required={true}
        register={register}
        error={errors?.phoneNumber?.message}
        inputComponent={TextMaskCustom}
      />

     <button onClick={handleSubmit(onSubmit)}>Submit</button>
     ...
  );
}


1

There are 1 best solutions below

0
F.E On

Seems like you are missing passing value to Input component.

IMaskInput needs value attribute otherwise it gives empty with the onAccept event.

so.

  const {
    register,
    formState: { errors },
    handleSubmit,
    watch
  } = useForm({
    resolver: yupResolver(schema)
  });

 ...
 const phoneNumber = watch('phoneNumber')
 ...

 <Input
    name="cpf"
    value={phoneNumber}
    required={true}
    register={register}
    error={errors?.phoneNumber?.message}
    inputComponent={TextMaskCustom}
 />

I believe this will help you.