DEV Community

Mayu Hayakawa
Mayu Hayakawa

Posted on

What is formik-yup ?

Hi! It's Mayu.

In this post, I will explain how to use formik-yup.
This is a very useful framework for creating and validating Forms in React.
https://www.npmjs.com/package/formik-yup

How to use formik to create form?

Formik allows us to create form function easily

1)install

npm i formik-yup
Enter fullscreen mode Exit fullscreen mode

2)import

import { useFormik } from  "formik";
Enter fullscreen mode Exit fullscreen mode

3)set the initial value

const formik = useFormik({
    initialValues: {
        // you can set values as much you need
        name: '',
        email: '',
        country: 'Canada',
        terms: ''
    }
});
Enter fullscreen mode Exit fullscreen mode

4) set formik value and handleChange on each input fields

<input 
    type="text" 
    name="name" 
    value={formik.values.name}
    onChange={formik.handleChange}
/>
Enter fullscreen mode Exit fullscreen mode

5) also you can set submit function with handleSubmit() on form tag

<form onSubmit={formik.handleSubmit}>
    <!-- input field -->
</form>
Enter fullscreen mode Exit fullscreen mode

6) then you can get user's input data with setting submit form inside useFormik function

const formik = useFormik({
    onSubmit: (values) => {
        console.log(values); //you can get input data as object
    }
}
Enter fullscreen mode Exit fullscreen mode

Way to use Yup in form

Yup is a schema builder for validation.

1)import

import * as Yup from "yup";
Enter fullscreen mode Exit fullscreen mode

2)set validate form inside useFormik Function

const formik = use Formik({
    validationSchema: Yup.object({
      name: Yup.string()
        .max(20, 'Name must be 20 characters or less')
        .required("Name is repuired"),
      terms: Yup.array()
        .required('Terms of service is must be checked')
    }),
})
Enter fullscreen mode Exit fullscreen mode

3) then when the user submits data with something wrong, it returns 'formik.errors' object has the error message.

Top comments (0)