Skip to content

jannikbuschke/formik-antd

Repository files navigation

Build Status GitHub stars npm All Contributors license

CodeSandbox

✨ Ant Design 4 and compatability

Ant Design 4 is landing soon. A beta that works with Ant Designs release candidate is available (v2.*-beta). Version 1 of this library supports Ant Design v3. Version 2 of this library supports Ant Design 4. Both v1 and v2 of this library work with formik v1 and v2.

⚠️ new npm package name: formik-antd ⚠️

from version 1.6 and onwards this library is published under formik-antd, all previous versions are available under @jbuschke/formik-antd. In order to upgrade: change the referenced package name in your package.json as well as all imports. I.e. replace import { Input } from "@jbuschke/formik-antd with import { Input } from "formik-antd.

formik-antd

Simple declarative bindings for Ant Design and Formik.

Core Concept

This library enriches several Ant Design components with a required name: string property that connects them to a Formik form field. It is quite simple. Instead of importing your form components from antd, you need to import them from 'formik-antd' and the name prop. Now the component is connected/synced with the corresponding Formik field!

The Ant Design components are feature rich and provide a lot of props to customize their visual presentation. These features and also their apis stay exactly the same. Visit their documentation to learn more.

Example:

import React from 'react'
import { Form, Input, InputNumber, Checkbox } from 'formik-antd'
import { Formik } from 'formik'

function App() {
  return (
    <Formik
      initialValues={{ firstName: '', age: 20, newsletter: false }}
      render={() => (
        <Form>
          {/* every formik-antd component must have the 'name' prop set: */}
          <Input name='firstName' placeholder='First Name' />
          {/* the rest of the api stays as is */}
          <InputNumber name='age' min={0} />
          <Checkbox name='newsletter'>Newsletter</Checkbox>
        </Form>
      )}
    />
  )
}

Getting started

npm install formik-antd

Add import "antd/dist/antd.css" to your index.js file (or look at https://ant.design/docs/react/getting-started for other options).

Core Components

Name Props
βœ… AutoComplete { name, validate?, fast? } & AutoCompleteProps
βœ… Cascader { name, validate?, fast? } & CascaderProps
βœ… Checkbox { name, validate?, fast? } & CheckboxProps
βœ… Checkbox.Group { name, validate?, fast? } & CheckboxGroupProps
βœ… DatePicker { name, validate?, fast? } & DatePickerProps
βœ… DatePicker.WeekPicker { name, validate?, fast? } & WeekPickerProps
βœ… DatePicker.RangePicker { name, validate?, fast? } & RangePickerProps
βœ… DatePicker.MonthPicker { name, validate?, fast? } & MonthPickerProps
βœ… Input { name, validate?, fast? } & InputProps
βœ… InputNumber { name, validate?, fast? } & InputNumberProps
βœ… Input.Password { name, validate?, fast? } & InputPasswordProps
βœ… Input.TextArea { name, validate?, fast? } & Input.TextAreaProps
βœ… Mention { name, validate?, fast? } & MentionProps
βœ… Radio.Group { name, validate?, fast? } & RadioGroupProps
βœ… Rate { name, validate?, fast? } & RateProps
βœ… Select { name, validate?, fast? } & SelectProps
βœ… Slider { name, validate?, fast? } & SliderProps
βœ… Switch { name, validate?, fast? } & SwitchProps
βœ… Table { name, fast? } & TableProps
βœ… TimePicker { name, validate?, fast? } & TimePickerProps
βœ… Transfer { name, validate?, fast? } & TransferProps
βœ… TreeSelect { name, validate?, fast? } & TreeSelectProps

Submitting and Resetting Forms

Directly under each <Formik> container a <Form> component should be placed. This component composes the functionality provided by Ant Designs (https://ant.design/components/form/) as well as Formiks (https://jaredpalmer.com/formik/docs/api/form) <Form> components:

import React from 'react'
import { Form, SubmitButton, ResetButton /* ... */ } from 'formik-antd'
import { Formik } from 'formik'

function App() {
  return <Formik initialValues={/* ... */} onSubmit={/* ... */}>
    <Form>
      {/* ... */}
      <SubmitButton />
      <ResetButton />
    </Form>
  </Formik>
}

The SubmitButton and ResetButton will disable automatically depending on form state. The ResetButton is enabled if the form is dirty. The SubmitButton is enabled if the form is valid or if it is not dirty. If you do want to control the disable behavior yourself you can provide the (usual ant design) disable: boolean prop. I.e. <SubmitButton disabled={false} /> will make the button always be enabled.

Form- and Field-level Validation

Formik provides form- and field-level validation callbacks to provide validation logic. How to validate is neither part of formik nor of this library.

Form-level validation is done by setting formiks validate prop. Field-level validation is optional available on the components. Additional to the name prop formiks optional validate?: (value: any) => undefined | string | Promise<any> is added to all core components to allow field-level validation. There is one special case to be aware of when using field-level validation: When using the Form.Item component with another Antd-field component, the validate prop has to be added to the Form.Item, not the input component:

<Form.Item name='firstName' validate={validator}>
  <Input name='firstName' />
</Form.Item>

Rendering Validation Feedback

Showing validation messages can be accomplished with the Form.Item component (or FormItem which is the same). It

  • renders error messages if the field has been touched and the corresponding field has a validation error (and changes the border color of enclosed input component to red).
  • renders a green success icon messages if it's showValidateSuccess: boolean prop is set to true, the field has been touched and the corresponding field does not have a validation error.
  • exposes some layout features and a label (visit https://ant.design/components/form/ for the details).
<Form.Item name='firstName'>
  <Input name='firstName' />
</Form.Item>

FastField support

Formik allows performance optimizations through the <FastField/> component. Please read the formik docs on when to use such an optimization (usually you don't and maybe should not optimize, unless you encounter performance issues in production). To opt-in to FastField support, all formik-antd components provide an optional fast?: boolean prop. Setting this to true enables the optimization:

<Input name='firstName' fast={true} />

Table

The table components comes with additional helper buttons to add and delete rows. An example can be seen in the codesandbox.

Two additional helper components to submit and reset forms are provided: SubmitButton and ResetButton. Both render an Ant Design button and can be customized accordingly (docs). The ResetButton is disabled if the form is not dirty. To override the default behavior provide the disable: boolean prop.

Lists and Nested objects

Nested objects and arrays can be accessed with lodash-like bracket syntax as described in the Formik documentation.

<Input name='friends[0].firstName' />

ES imports

If you do not want to import the full ant design library and its stylesheet (in order to reduce the bundle size) you can import specific components and their stylesheet by their path, as it is described in the antd documentation https://ant.design/docs/react/getting-started#Import-on-Demand

import Input from 'formik-antd/es/input'
import 'formik-antd/es/input/style'

Some build tools like webpack are now able to "tree shake", meaning unused code from ant design will not be bundled.

As writing imports like this is a little cumbersome there is a babel import helper: https://github.com/ant-design/babel-plugin-import. In create-react-app projects babel plugins do not work out of the box. With third party projects like customize-cra and react-app-rewired we are able to change the webpack config. Be warned though, the team behind create-react-app does not support this scenario, so if you run into problems you are on your own.

npm install babel-plugin-import customize-cra react-app-rewired --save-dev

config-overrides.js

const path = require('path')
const { override, fixBabelImports } = require('customize-cra')

module.exports = override(
    fixBabelImports('antd', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
    }),
    fixBabelImports('formik-antd',
        {
            libraryName: 'formik-antd',
            libraryDirectory: 'es',
            style: "css",
        },
    )
);

package.json

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build"
  }

Treeshaking

Treeshaking with ant design is currently kind of broken, as generally all icons are imported. This will be fixed as of ant design v4 (might be ready in 2019).

Playground & Contributions

If you want to dig into the source code and test locally you can use https://github.com/jannikbuschke/Formik-antd-playground (clone with the --recursive flag and follow the README, its pretty simple).

TypeScript

Types are included.

Typechecking limitations

Form values currently cannot be typechecked (at least to my knowledge). For example the following ideally would give a compile error:

<Formik<{name:string}> initialValues={{name:""}}>
  <Input name="naem" />
</Formik>

Typescript cannot (yet) enforce types of children. In the future this hopefully will be possible.

License

MIT

Contributors

Special thanks to all contributors:


Nile Daley

πŸ’»

James W Mann

πŸ’»

Jannik Buschke

πŸ’»

Lars-JΓΈrgen Kristiansen

πŸ’»

Adam

πŸ’»

jeessy2

πŸ’»

Pavan Agrawal

πŸ“–

Khartir

πŸ’»

Yury Kozhenov

πŸ’»

Tonye Jack

πŸ’»

Edon Gashi

πŸš‡

Roman Tsegelskyi

πŸ’»

Daniel Schulz

πŸ’»

Harry Green

πŸ“–

Daniel Huth

πŸ’»

Gabriel Berlanda

πŸ’» πŸ“–

Alexandre Giard

πŸ€”

kissthom

πŸ›

This project follows the all-contributors specification. Contributions of any kind welcome!