Skip to main content

Advanced Form Handling with Formik (Part 1): Introduction to a Popular Form Library #77

📖 Introduction

Following our exploration of Form Validation: The Basics, this article introduces Formik, a popular and powerful library for building forms in React. We will learn why libraries like Formik are so useful and how they can help us write cleaner, more maintainable form code.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • Controlled Components
  • Basic form validation techniques
  • npm or yarn for installing packages

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The "Why" of Formik: Understanding the problems Formik solves and the benefits of using a form library.
  • Core Concepts: An introduction to Formik's core concepts, including the useFormik hook.
  • Core Implementation: How to build a simple form using Formik to manage state and submission.
  • Basic Validation: How to add basic validation to a Formik form.

🧠 Section 1: The Core Concepts of Formik

Building forms from scratch in React can be verbose. You have to manage the form's state, handle submission, and implement validation, all of which can lead to a lot of boilerplate code.

Formik simplifies this process by:

  • Managing the form's state for you.
  • Providing helper functions for common tasks like handling changes and submissions.
  • Making it easy to implement complex validation logic.

At its core, Formik provides a hook called useFormik that gives you everything you need to manage a form.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's see how to build a simple form with Formik.

2.1 - Installation

First, you need to install Formik in your project:

npm install formik

2.2 - Your First Formik Form

Here is a basic example of a login form built with Formik:

// code-block-1.jsx
import React from 'react';
import { useFormik } from 'formik';

function LoginForm() {
const formik = useFormik({
initialValues: {
email: '',
password: '',
},
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
});

return (
<form onSubmit={formik.handleSubmit}>
<div>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
onChange={formik.handleChange}
value={formik.values.password}
/>
</div>
<button type="submit">Submit</button>
</form>
);
}

export default LoginForm;

Step-by-Step Code Breakdown:

  1. import { useFormik } from 'formik';: We import the useFormik hook from the Formik library.
  2. const formik = useFormik({ ... });: We call the useFormik hook with a configuration object.
    • initialValues: An object that defines the initial values of our form fields.
    • onSubmit: A function that will be called when the form is submitted.
  3. formik.handleSubmit: We pass this to the onSubmit prop of our form.
  4. formik.handleChange: We pass this to the onChange prop of our inputs.
  5. formik.values: This object contains the current values of our form fields.

2.3 - Adding Basic Validation

Formik has built-in support for validation. You can add a validate function to your useFormik configuration.

// code-block-2.jsx
const formik = useFormik({
initialValues: {
email: '',
password: '',
},
validate: (values) => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
if (!values.password) {
errors.password = 'Required';
}
return errors;
},
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
});

Now, the formik object will also contain an errors object with any validation errors. We can use this to display error messages to the user.

// code-block-3.jsx
// ... inside the return statement
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.errors.email ? <div>{formik.errors.email}</div> : null}

💡 Conclusion & Key Takeaways

In this article, we've been introduced to Formik and seen how it can simplify form management in React. By handling state and providing helper functions, Formik allows us to write cleaner and more maintainable form code.

Let's summarize the key takeaways:

  • Formik is a library that simplifies form management in React.
  • The useFormik hook is the core of Formik, providing everything you need to manage a form.
  • Formik has built-in support for validation, making it easy to provide feedback to the user.

Challenge Yourself: To solidify your understanding, try to add a "confirm password" field to the form with validation to ensure it matches the password field.


➡️ Next Steps

You now have a basic understanding of Formik. In the next article, "Advanced Form Handling with Formik (Part 2)", we will explore more advanced features of Formik, including how to use the <Formik />, <Form />, <Field />, and <ErrorMessage /> components, and how to integrate with the popular validation library, Yup.

Thank you for your dedication. Stay curious, and happy coding!


glossary

  • Formik: A popular library for building forms in React.
  • useFormik: A React hook provided by Formik for managing form state and submission.
  • Boilerplate Code: Sections of code that have to be included in many places with little or no alteration.

Further Reading