"mui-one-time-password-input" is not working with "formik"

157 views Asked by At

I am working on a Next.js Project, and I have to use mui-one-time-password-input library for OTP input. and for form validation I am using formik.

Now, when I try to apply value and onChange properties to MuiOtpInput component; Somehow, it is not accepting any input I provide in that MuiOtpInput field.

const OtpForm = () => {
    const formik = useFormik({
        initialValues: {
            otp: null,
            submit: null
        },
        validationSchema: Yup.object({
            otp: Yup
                .string()
                .length(6, 'Must be a valid OTP')
                .required('OTP is required')
        })
    });

    return (
        <form>
            <MuiOtpInput
                TextFieldsProps={{
                    placeholder: '-'
                }}
                onComplete={formik.handleSubmit}
                onChange={formik.handleChange}
                value={formik.values.otp}
                length={OTP_LENGTH}
            />
        </form>
    );
};

This works though...

const OtpForm = () => {
    const [otp,setOtp] = useState('')

    return (
        <form>
            <MuiOtpInput
                TextFieldsProps={{
                    placeholder: '-'
                }}                
                onChange={(val) => setOtp(val)}
                value={otp}
                length={OTP_LENGTH}
            />
        </form>
    );
};
1

There are 1 answers

0
alireza hamzeh On

It seems that MuiOtpInput lacks support for the 'name' property, which might be causing the issue. To fix this issue you can use formik.setFieldValue(fieldName, value), Here's an example code snippet:

const OtpForm = () => {
    const formik = useFormik({
        initialValues: {
            otp: null,
            submit: null
        },
        validationSchema: Yup.object({
            otp: Yup
                .string()
                .length(6, 'Must be a valid OTP')
                .required('OTP is required')
        })
    });

    return (
        <form>
            <MuiOtpInput
                TextFieldsProps={{
                    placeholder: '-'
                }}
                onComplete={formik.handleSubmit}
                onChange={(value) => formik.setFieldValue("otp", value)}
                value={formik.values.otp}
                length={OTP_LENGTH}
            />
        </form>
    );
};