Advanced Form Handling with Formik (Part 2): Building a Complex Form #78
📖 Introduction
Following our introduction to Advanced Form Handling with Formik (Part 1), this article takes a deeper dive into Formik's capabilities. We will learn how to use Formik's declarative components (<Formik />, <Form />, <Field />, and <ErrorMessage />) and integrate with the Yup library for powerful and flexible validation.
📚 Prerequisites
Before we begin, please ensure you have a solid grasp of the following concepts:
- All concepts from Part 1 of this series.
npmoryarnfor installing packages.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ Declarative Components: How to use the
<Formik />,<Form />,<Field />, and<ErrorMessage />components to write cleaner and more concise form code. - ✅ Yup for Validation: How to integrate the Yup library to create powerful and readable validation schemas.
- ✅ Building a Complex Form: We will build a complete registration form with multiple fields and complex validation rules.
🧠 Section 1: The Core Concepts of Formik Components and Yup
While the useFormik hook is great, Formik also provides a set of components that can make your form code even more declarative and easier to read.
<Formik />: The root component that manages the form's state and submission.<Form />: A wrapper for the HTML<form>element that automatically hooks into Formik'shandleSubmit.<Field />: A component that connects an input to the Formik state.<ErrorMessage />: A component that displays the validation error for a specific field.
Yup is a JavaScript schema builder for value parsing and validation. When combined with Formik, it allows you to define your validation rules in a separate object, keeping your component code clean and focused.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Let's build a registration form with Formik and Yup.
2.1 - Installation
First, you need to install Formik and Yup:
npm install formik yup
2.2 - Creating the Validation Schema with Yup
Let's create a validationSchema.js file to define our validation rules.
// validationSchema.js
import * as Yup from 'yup';
export const 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'),
password: Yup.string()
.min(8, 'Password must be at least 8 characters')
.required('Required'),
confirmPassword: Yup.string()
.oneOf([Yup.ref('password'), null], 'Passwords must match')
.required('Required'),
});
2.3 - Building the Form with Formik Components
Now, let's build our registration form using Formik's declarative components.
// code-block-1.jsx
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import { validationSchema } from './validationSchema';
function RegistrationForm() {
return (
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
password: '',
confirmPassword: '',
}}
validationSchema={validationSchema}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
<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>
<div>
<label htmlFor="password">Password</label>
<Field name="password" type="password" />
<ErrorMessage name="password" component="div" className="error" />
</div>
<div>
<label htmlFor="confirmPassword">Confirm Password</label>
<Field name="confirmPassword" type="password" />
<ErrorMessage name="confirmPassword" component="div" className="error" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
export default RegistrationForm;
Step-by-Step Code Breakdown:
<Formik />: We wrap our form in the<Formik />component and provide theinitialValues,validationSchema, andonSubmitprops.<Form />: This component automatically hooks into theonSubmitfunction provided to<Formik />.<Field />: We use the<Field />component for each of our inputs. It automatically handles theonChange,onBlur, andvalueprops.<ErrorMessage />: This component displays the validation error for the corresponding<Field />.
💡 Conclusion & Key Takeaways
In this article, we've learned how to use Formik's declarative components and the Yup library to build complex forms with powerful validation. This approach leads to cleaner, more readable, and more maintainable code.
Let's summarize the key takeaways:
- Formik's declarative components (
<Formik />,<Form />,<Field />,<ErrorMessage />) provide a clean and concise way to build forms. - Yup is a powerful library for creating readable and maintainable validation schemas.
- By combining Formik and Yup, you can build complex forms with ease.
Challenge Yourself: To solidify your understanding, try to add a checkbox to the form for accepting terms and conditions, with validation to ensure it is checked.
➡️ Next Steps
You now have a solid understanding of how to build complex forms with Formik and Yup. In the next article, "Another Option: React Hook Form (Part 1)", we will explore another popular form library and compare its approach to Formik's.
Thank you for your dedication. Stay curious, and happy coding!
glossary
- Yup: A JavaScript schema builder for value parsing and validation.
- Declarative Programming: A programming paradigm that expresses the logic of a computation without describing its control flow.
- Schema: A representation of a plan or theory in the form of an outline or model.