logo
eng-flag

Formik Cheatsheet

Formik is a popular form library for React that helps with the three most annoying parts of form development: getting values in and out of form state, validation and error messages, and handling form submission. This cheatsheet provides an overview of commonly used Formik concepts and components.

Table of Contents

  1. Basic Usage
  2. Formik Components
  3. Form Submission
  4. Validation
  5. Error Handling
  6. Field Arrays
  7. useFormik Hook
  8. Tips and Tricks

Basic Usage

import React from 'react';
import { Formik, Form, Field } from 'formik';

const BasicForm = () => (
  <Formik
    initialValues={{ email: '', password: '' }}
    onSubmit={(values, { setSubmitting }) => {
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
  >
    {({ isSubmitting }) => (
      <Form>
        <Field type="email" name="email" />
        <Field type="password" name="password" />
        <button type="submit" disabled={isSubmitting}>
          Submit
        </button>
      </Form>
    )}
  </Formik>
);

Formik Components

Formik

<Formik
  initialValues={{ /* initial form values */ }}
  validationSchema={/* Yup schema */}
  onSubmit={(values, actions) => {
    // Handle form submission
  }}
>
  {/* Form content */}
</Formik>

Form

<Form>
  {/* Form fields */}
</Form>

Field

<Field type="text" name="firstName" />
<Field as="textarea" name="bio" />
<Field as="select" name="color">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

ErrorMessage

<ErrorMessage name="email" component="div" />

Form Submission

<Formik
  onSubmit={(values, { setSubmitting }) => {
    // Submit logic here
    setSubmitting(false);
  }}
>
  {({ isSubmitting }) => (
    <Form>
      {/* Form fields */}
      <button type="submit" disabled={isSubmitting}>
        Submit
      </button>
    </Form>
  )}
</Formik>

Validation

With Yup

import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(8, 'Too Short!').required('Required'),
});

<Formik
  validationSchema={validationSchema}
  // ...
>
  {/* ... */}
</Formik>

Manual Validation

<Formik
  validate={values => {
    const errors = {};
    if (!values.email) {
      errors.email = 'Required';
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$/i.test(values.email)) {
      errors.email = 'Invalid email address';
    }
    return errors;
  }}
  // ...
>
  {/* ... */}
</Formik>

Error Handling

<Formik
  // ...
>
  {({ errors, touched }) => (
    <Form>
      <Field type="email" name="email" />
      {errors.email && touched.email ? <div>{errors.email}</div> : null}
      {/* ... */}
    </Form>
  )}
</Formik>

Field Arrays

import { FieldArray } from 'formik';

<Formik
  initialValues={{ friends: [''] }}
  // ...
>
  {({ values }) => (
    <Form>
      <FieldArray name="friends">
        {({ insert, remove, push }) => (
          <div>
            {values.friends.length > 0 &&
              values.friends.map((friend, index) => (
                <div key={index}>
                  <Field name={`friends.${index}`} />
                  <button type="button" onClick={() => remove(index)}>X</button>
                </div>
              ))}
            <button type="button" onClick={() => push('')}>
              Add Friend
            </button>
          </div>
        )}
      </FieldArray>
    </Form>
  )}
</Formik>

useFormik Hook

import { useFormik } from 'formik';

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

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

Tips and Tricks

Resetting Form

<Formik
  // ...
  onSubmit={(values, { resetForm }) => {
    // Submit logic
    resetForm();
  }}
>
  {/* ... */}
</Formik>

Conditional Fields

<Formik
  // ...
>
  {({ values }) => (
    <Form>
      <Field type="checkbox" name="toggle" />
      {values.toggle && (
        <Field type="text" name="conditionalField" />
      )}
    </Form>
  )}
</Formik>

Custom Input Component

const MyInput = ({ field, form, ...props }) => {
  return <input {...field} {...props} />;
};

<Field name="myField" component={MyInput} />

Accessing Formik Context

import { useFormikContext } from 'formik';

const SubmitButton = () => {
  const { isSubmitting } = useFormikContext();
  return (
    <button type="submit" disabled={isSubmitting}>
      Submit
    </button>
  );
};

2024 © All rights reserved - buraxta.com