DEV Community

Discussion on: Form Validation Using Formik and Yup in React

Collapse
 
victorocna profile image
Victor Ocnarescu

Great article, I really enjoyed reading it! Me and my dev team always choose Formik & Yup for form handling. And I might have a suggestion that can make your code even more beautiful.

Instead of

<Form>
    <Field name="firstname" />
    {
     errors.firstname && touched.firstname ? (<div>{errors.firstname}</div>) : null
    }
</Form>
Enter fullscreen mode Exit fullscreen mode

why not create a new component that will handle the errors like so

<Form>
    <Field name="firstname" />
    <ErrorField name="firstname" />
</Form>
Enter fullscreen mode Exit fullscreen mode

The ErrorField component can access the useFormikContext hook for errors and touched states.

const ErrorField = (name) => {
    const { errors, touched } = useFormikContext();
    if (!errors[name] || !touched[name]) {
        return null;
    }

    return <div>{errors[name]}</div>
}
Enter fullscreen mode Exit fullscreen mode

Let me know what you think. Cheers!

Collapse
 
nduyvu1511 profile image
Vu

That's great