Using and Customizing Formik for Forms

Using and Customizing Formik for React.js Forms

Formik is a powerful library within the React ecosystem that simplifies the process of building forms. It handles form state management, validation, and submission, significantly reducing boilerplate code and enhancing the scalability of form logic in your applications.

Basic Form Setup

To set up a basic form with Formik, define your form structure using the Formik, Form, and Field components from the Formik library. Here's a basic example:

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

const BasicForm = () => (
  <Formik
    initialValues={{
      fullname: 'John Doe',
      email: '[email protected]',
      color: 'green',
    }}
    onSubmit={(values) => {
      console.log(values);
    }}
  >
    <Form>
      <Field name='fullname' placeholder='Full name' />
      <Field type='email' name='email' placeholder='Email' />
      <Field name='color' as='select'>
        <option value='red'>Red</option>
        <option value='green'>Green</option>
        <option value='blue'>Blue</option>
      </Field>
    </Form>
  </Formik>
);

export default BasicForm;

In this example, we use three key components for creating forms with Formik:

  • Formik: The component that holds the form logic and state.
  • Form: A component that automatically hooks into Formik’s handleSubmit and handleReset.
  • Field: A component that automatically hooks into Formik’s handleChange, handleBlur, and value/state management.

Example usage Formik in our project

In the example below, Formik manages a form for creating a new user, typically found in frontend/src/pages/users/users-new.tsx:

import { Formik, Form, Field } from 'formik';
import { CardBox, FormField, SwitchField, FormImagePicker } from '../../components';

const initialValues = {
  firstName: '',
  lastName: '',
  phoneNumber: '',
  email: '',
  disabled: false,
  avatar: [],
};

const UserForm = () => (
  <CardBox>
    <Formik
      initialValues={initialValues}
      onSubmit={(values) => console.log(values)}
    >
      <Form>
        <FormField label='First Name'>
          <Field name='firstName' placeholder='First Name' />
        </FormField>

        <FormField label='Last Name'>
          <Field name='lastName' placeholder='Last Name' />
        </FormField>

        <FormField label='Phone Number'>
          <Field name='phoneNumber' placeholder='Phone Number' />
        </FormField>

        <FormField label='E-Mail'>
          <Field name='email' placeholder='E-Mail' />
        </FormField>

        <FormField label='Disabled' labelFor='disabled'>
          <Field name='disabled' id='disabled' component={SwitchField} />
        </FormField>

        <FormField label='Avatar'>
          <Field
            name='avatar'
            component={FormImagePicker}
            path='users/avatar'
          />
        </FormField>

        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </CardBox>
);

export default UserForm;

Customizing Inputs and Display

With Formik, you are free to use any UI framework or custom components to render your form elements.

For example, you can use already defined components like SelectField, SelectFieldMany that are located in frontend/src/components.

Here's an example of integrating Formik with custom select components SelectField and SelectFieldMany:

import { Formik, Form, Field } from 'formik';
import { SelectField, SelectFieldMany } from '../../components';

const CustomForm = () => (
  <Formik
    initialValues={{ product: '', categories: [] }}
    onSubmit={(values) => console.log(values)}
  >
    <Form>
      <Field
        name='product'
        component={SelectField}
        options={[{ id: '1', value: 'Product 1' }, { id: '2', value: 'Product 2' }]}
        itemRef='products'
      />

      <Field
        name='categories'
        component={SelectFieldMany}
        options={[{ id: '1', value: 'Category 1' }, { id: '2', value: 'Category 2' }]}
        itemRef='categories'
        showField='title'
      />

      <button type="submit">Submit</button>
    </Form>
  </Formik>
);

export default CustomForm;

The whole code of this component use can be found in frontend/src/pages/users/users-new.tsx

Documentation Reference

For more advanced use cases and API details, refer to the official Formik documentation.