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>
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;
}
After this, you'll get a login form same as this
Initialize formik default states
Lets import the useFormik
first from the formik.
import { useFormik } from "formik";
Now you can initialize the initialValues of form using useFormik hook .
const formik = useFormik({
initialValues: {
email: "",
password: ""
},
)}
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}
/>
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";
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,
)};
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}
Now our form looks like this with validation errors
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);
}
});
and pass formik handleSubmit function to your form like this
<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
Top comments (10)
Formik is indeed awesome. Have you ever tried Formik Fields? They automatically bind
onChange
,onBlur
andvalue
to your input (and you don't have to declare them all the time).Without Formik Fields:
With Formik Fields:
Incredible I will give it try sir .
I respectfully disagree. How about touched fields handling? Or error messages and states? Submit count for your forms? Even validation that is not your basic HTML5 validation? These are all handled by Formik by default and you don't have to worry about them.
My forms have become really clean after I started using this library. I cannot recommend Formik enough.
The drawback to using "basic" form logic instead of a specific package like Formik is it can get complicated along the way. And most of the times it does get more complicated.
Imagine you start a simple login form, everything is great. Basic HTML5 validation works. Then your client comes up and wants to display an error message tied to the username field, only when the form was already submitted and the username does not exist (check the login on Netflix for this exact scenario).
Now here is the part it gets messy. You don't exactly know what to do. Should you implement these yourself? Or maybe a package like Formik? It did not get too complicated, it's still a form with 2 fields: username and password.
Of course, you are right about the HTML5 validation. You can get that for free in every browser and it improves UX. But Formik (or a similar package that improves forms) is the next best thing. Forms get messier and messier as your projects evolve.
Yes you get a point .
Thanks for this guide! Detailed yet very quick, much appreciated. 💯
It's my pleasure 😊.
Thanks for the article! I especially like its brevity. Personally I hate making forms by the way )
It's my pleasure Sir 😊.
Yes you are right bro .Just I want to cover fundamentals of formik and yup .My goal not for login it's for fundamentals ....