Written by: Geoffrey Callaghan

formik tutorial

Formik Tutorial

Formik is a popular library for managing forms in React applications. It simplifies form handling by managing state, validation, and submission processes. Here’s a step-by-step tutorial to help you get started with Formik.

Step 1: Setup Your React Application

First, make sure you have a React application set up. You can create a new one using Create React App if you don’t already have one:

npx create-react-app my-formik-app
cd my-formik-app

Step 2: Install Formik

Install Formik using npm or yarn:

npm install formik
# or
yarn add formik

Step 3: Basic Usage of Formik

Let’s create a simple form to collect user information (name and email).

  1. Create a new component (e.g., MyForm.js):
import React from 'react';
import { useFormik } from 'formik';

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

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

export default MyForm;
  1. Include this component in your main application file (e.g., App.js):
import React from 'react';
import MyForm from './MyForm';

const App = () => (
  <div>
    <h1>My Formik Form</h1>
    <MyForm />
  </div>
);

export default App;

Step 4: Adding Validation

Formik provides an easy way to add validation to your forms. We’ll use Yup, a popular validation library.

  1. Install Yup:
npm install yup
# or
yarn add yup
  1. Update your form component to include validation:
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const MyForm = () => {
  const formik = useFormik({
    initialValues: {
      name: '',
      email: '',
    },
    validationSchema: Yup.object({
      name: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      email: Yup.string()
        .email('Invalid email address')
        .required('Required'),
    }),
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <div>
        <label htmlFor="name">Name</label>
        <input
          id="name"
          name="name"
          type="text"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.name}
        />
        {formik.touched.name && formik.errors.name ? (
          <div>{formik.errors.name}</div>
        ) : null}
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          name="email"
          type="email"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.email}
        />
        {formik.touched.email && formik.errors.email ? (
          <div>{formik.errors.email}</div>
        ) : null}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

Step 5: Enhancing the Form

Formik provides more features to handle complex forms. Here’s a brief overview of some additional functionalities:

  1. Field Component: Instead of manually wiring up inputs, you can use Formik’s Field component.
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const MyForm = () => (
  <Formik
    initialValues={{ name: '', email: '' }}
    validationSchema={Yup.object({
      name: Yup.string()
        .max(15, 'Must be 15 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);
    }}
  >
    <Form>
      <div>
        <label htmlFor="name">Name</label>
        <Field name="name" type="text" />
        <ErrorMessage name="name" />
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <Field name="email" type="email" />
        <ErrorMessage name="email" />
      </div>
      <button type="submit">Submit</button>
    </Form>
  </Formik>
);

export default MyForm;
  1. Handling Arrays: Use Formik’s FieldArray for managing arrays of fields.

  2. Dynamic Forms: Create forms that can add/remove fields dynamically based on user input.

Conclusion

Formik is a powerful tool for handling forms in React applications, providing an easy way to manage form state, validation, and submission. With its integration with Yup, you can handle complex validation logic with ease. This tutorial covers the basics, but Formik has many more features that you can explore in its official documentation.