Simple way to write forms in React with Formik

hamid2117

Hamid

Posted on September 8, 2021

Simple way to write forms in React with Formik

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

 <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>
Enter fullscreen mode Exit fullscreen mode

and styled it like this

.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;
}

Enter fullscreen mode Exit fullscreen mode

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

image

Initialize formik default states

Lets import the useFormik first from the formik.

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

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

const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
)}
Enter fullscreen mode Exit fullscreen mode

let's apply formik to our input fields .

   ...
          <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}
          />
Enter fullscreen mode Exit fullscreen mode

Apply validations on login fields

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

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

Then I added validationSchema for my login fields

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,
)};
Enter fullscreen mode Exit fullscreen mode

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 .

{formik.touched.email && formik.errors.email ? (
         <span className="error">{formik.errors.email}</span>
) : null}
Enter fullscreen mode Exit fullscreen mode

Now our form looks like this with validation errors

image

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 .

const formik = useFormik({
    initialValues: {
      email: "",
      password: ""
    },
    validationSchema,
    onSubmit: (values) => {
      setIsLoggedIn(true);
    }
  });
Enter fullscreen mode Exit fullscreen mode

and pass formik handleSubmit function to your form like this

<form className="form" onSubmit={formik.handleSubmit}>
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
hamid2117
Hamid

Posted on September 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related