How to use formik with useFormik prop in react
Tags: react, beginners, javascript, css
Published: 2021-01-28 16:06:16

Formik is a super cool library and I use it every time. So today I am writing this post for beginners and it covers the use of formik on the simple login form. 

I'll cover these things here
* [Create and style a basic login form](#step-1)
* [Initialize formik default states](#step-2)
* [Apply validation on login fields](#step-3)
* [Write submit form function](#step-4)

##Create and style a login form <a name="step-1"></a>
I created login form like this
```javascript
      <form className="form">
        <div className="field">
          <label htmlFor="email">Email Address</label>
          <input
            id="email"
            name="email"
            type="email"
          />
        </div>
        <div className="field">
          <label htmlFor="password">Password</label>
          <input
            id="password"
            name="password"
            type="password"
          />
        </div>
        <button type="submit" className="submit-btn">
          Login
        </button>
      </form>
```
and styled it like this
```javascript
.form {
  width: 300px;
  display: flex;
  flex-direction: column;
  margin-top: 50px;
  background-color: #ddd;
  border-radius: 8px;
  padding: 10px;
}
.field {
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;
}
.submit-btn {
  align-self: flex-end;
  width: 80px;
}
```
After this, you'll get a login form same as this
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rbuxl9d8sbgzay91jy99.png)

##Initialize formik default states <a name="step-2"></a>
Lets import the `useFormik` first from the formik
```javascript
import { useFormik } from "formik";
```
Now you can create a formik object using `useFormik` hook and define your `initialValues` in it
```javascript
  const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    }
  });
```
let's use the formik `handleChange` function and pass formik values to our input fields
```javascript
     ...
          <input
            id="email"
            name="email"
            type="email"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.email}
          />
     ...
          <input
            id="password"
            name="password"
            type="password"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.password}
          />
```

##Apply validations on login fields <a name="step-3"></a>
I used `Yup` library to apply validations on my fields. You can use custom regex as well if you don't want to use `Yup` for some reason.
So first import `Yup` like this
```javascript
import * as Yup from "yup";
```
Then I added `validationSchema` for my login fields 
```javascript
 const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
    validationSchema: Yup.object().shape({
      email: Yup.string()
        .email("Invalid email address")
        .required("Please enter email"),
      password: Yup.string().required("Please enter password")
    }),
  });
```
Here `Yup` is validating if the values of the field are provided; if yes, then is it correct format or not.
So if any error happens according to our validation schema, it will be stored in formik's `errors` object and we can print it beside or below the field like this
```javascript
     {formik.touched.email && formik.errors.email ? (
         <span className="error">{formik.errors.email}</span>
     ) : null}
```
Now our form looks like this with validation errors
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yz50t2f4uvn7wu0r3oo0.png)

##Write submit form function <a name="step-4"></a>
The last step is to create submit function and perform your operation on formik values. You can navigate to the next screen, call API, or anything you want to do. I just set a state on submit and shown a message to a user on the login
```javascript
  const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
    validationSchema: Yup.object().shape({
      email: Yup.string()
        .email("Invalid email address")
        .required("Please enter email"),
      password: Yup.string().required("Please enter password")
    }),
    onSubmit: (values) => {
      setIsLoggedIn(true);
    }
  });
```
and pass formik `handleSubmit` function to your form like this
```javascript
<form className="form" onSubmit={formik.handleSubmit}>
```
and here your form is ready with field validations!!
You can find the full source code here
{% codesandbox formik-react-1p3ti %}