Formik is one of most popular React libraries, for managing forms and validations. It has inbuilt state-management system. The Fomik series of posts will cover all essential topics regarding form management using Formik.
Setup
As the very step we need to install the package and prepare our form. In this example we are using a simple login form.
yarn add formik
<form >
<input type="email" placeholder="Email" name="email" />
<input type="password" placeholder="Password" name="password" />
<button type='submit'>Sign In</button>
</form>
Formik hook
There are two ways to integrate formik with form, useFormik hook or use Formik component. We go with hook.
let’s configure the hook.
import { useFormik, Formik } from 'formik'
import * as Yup from 'yup'
const validationSchema = Yup.object({
email: Yup.string().email('Invalid email format').required('Required'),
password: Yup.string().required('Required'),
});
const formikLogin = useFormik({
initialValues: {
email: '',
password: '',
},
onSubmit: async values => {
console.log(values);
},
validationSchema
});
For the form formik will handle a couple of things, onSubmit, onChange, validation, error generation etc.
All we have to fill few formik values and functions call.
<form onSubmit={formikLogin.handleSubmit} >
<input type="email" placeholder="Email" name="email" value={formikLogin.values.email} onChange={formikLogin.handleChange} />
{formikLogin.errors.email ? <div>{formikLogin.errors.email}</div> : null}
<input type="password" placeholder="Password" name="password" value={formikLogin.values.password} onChange={formikLogin.handleChange} />
{formikLogin.errors.password ? <div>{formik.errors.password}</div> : null}
<button type='submit'>Sign In</button>
</form>
Note that form field’s name and formik field should be same.