Simple way to write forms in React with Formik
Tags: react, javascript, css, tutorial
Published: 2021-09-08 03:44:16

---
canonical_url: 'https://hamidmehmood.vercel.app/blog/formik-basic'
---
Formik is a best library and I use it every time. So today I am writing this post for fundamentals of formik and it covers the use of formik in simple way .

## Create and style a login form
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"
            placeholder="email"
          />
        </div>
        <div className="field">
          
          <input
            id="password"
            name="password"
            type="password"
            placeholder="password"
          />
        </div>
        <button type="submit" className="submit-btn">
          Login
        </button>
      </form>
```
and styled it like this

```css
.App {
  font-family: sans-serif;
  text-align: center;
  display: grid;
  place-items: center;
}
.form {
  width: 300px;
  display: grid;
  gap: 10px 0px;
  margin-top: 50px;
  background-color: #ddd;
  border-radius: 8px;
  padding: 10px;
}
.field {
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;
}
.submit-btn {
  width: 80px;
}
.error {
  color: red;
  font-size: 12px;
  justify-self: start;
  font-style: italic;
  padding-bottom: 10px;
  line-height: 3px;
}

```

After this, you'll get a login form same as this

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ynqrcet8s9wh07g4jh5a.png)
 
##Initialize formik default states
Lets import the `useFormik` first from the formik.


```javascript
import { useFormik } from "formik";
```

Now you can initialize the initialValues of form using useFormik hook .

```javascript
const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
)}
```

let's apply `formik` to our input fields .


```javascript
   ...
          <input
            id="email"
            name="email"
            type="email"
            placeholder="email"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.email}
          />
     ...
          <input
            id="password"
            name="password"
            type="password"
            placeholder="password"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.password}
          />
```

##Apply validations on login fields

I used `Yup` library to apply validations on my fields
So first import `Yup` like this .

```javascript
import * as Yup from "yup";
```
Then I added validationSchema for my login fields

```javascript
const validationSchema = yup.object({
    email: yup
      .string()
      .email('Please enter a valid email address')
      .required('Email is required'),
    password: yup
      .string()
      .min(8, 'Please enter strong password')
      .required('Password is required'),
  })
  const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
    validationSchema,
)};
```

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

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fe8sdpcymc4om8cv5d8b.png)
 
##Write submit form function

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,
    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

https://codesandbox.io/s/unruffled-tharp-uti1k?file=/src/App.js:727-781