Formik is a popular open-source library for React and React Native that simplifies building forms. It helps developers manage form state, handle validation, and submit forms without writing a lot of boilerplate code. Forms can be complex, involving numerous input fields, intricate validation rules, error messages, and submission logic. Formik abstracts away much of this complexity, providing a robust and easy-to-use API.
Key features and concepts of Formik include:
1. Managing Form State: Formik automatically keeps track of your form's values (e.g., `values`), visited fields (`touched`), and errors (`errors`). This state is provided via a `FormikContext` or directly through the `useFormik` hook.
2. Validation: It supports both synchronous and asynchronous validation. It integrates seamlessly with schema validation libraries like `Yup`, allowing you to define validation rules using a concise and powerful API. You can also define a custom `validate` function.
3. Submission Handling: Formik provides an `onSubmit` prop where you define what happens when the form is submitted. It also gives you helper functions like `setSubmitting` to manage the submission state.
4. Helper Components/Hooks: Formik offers several helper components (`<Formik>`, `<Form>`, `<Field>`, `<ErrorMessage>`) and hooks (`useFormik`, `useField`, `useFormikContext`) that streamline form development.
* `Formik` component (or `useFormik` hook): The core of Formik, it provides all the necessary props and state to its children.
* `Form` component: A simple wrapper around an HTML `<form>` element that automatically hooks into Formik's `handleSubmit`.
* `Field` component: Renders an HTML `<input>`, `<select>`, or `<textarea>` element and connects it to Formik's state. It manages `value`, `onChange`, `onBlur`, and `name` props.
* `ErrorMessage` component: Renders a validation error message for a specific field only if the field has been touched and has an error.
5. Reduced Boilerplate: By handling common form tasks, Formik significantly reduces the amount of repetitive code developers need to write for forms, making form management more maintainable and less error-prone.
In essence, Formik helps you abstract away the repetitive parts of form building, allowing you to focus on the unique logic and UI of your application's forms.
Example Code
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const SignupForm = () => {
return (
<Formik
initialValues={{ firstName: '', lastName: '', email: '' }}
validationSchema={Yup.object({
firstName: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('Required'),
lastName: Yup.string()
.max(20, 'Must be 20 characters or less')
.required('Required'),
email: Yup.string()
.email('Invalid email address')
.required('Required'),
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting }) => (
<Form>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" type="text" />
<ErrorMessage name="firstName" component="div" className="error" />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" type="text" />
<ErrorMessage name="lastName" component="div" className="error" />
</div>
<div>
<label htmlFor="email">Email Address</label>
<Field name="email" type="email" />
<ErrorMessage name="email" component="div" className="error" />
</div>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
);
};
export default SignupForm;
/*
To run this example:
1. Create a React project (e.g., using `create-react-app`)
2. Install Formik and Yup: `npm install formik yup` or `yarn add formik yup`
3. Replace your `App.js` content with this `SignupForm` component.
4. Optionally, add some basic CSS for error messages in your `index.css` or similar:
.error {
color: red;
font-size: 0.8em;
margin-top: 5px;
}
*/








Formik