Working with Antd Form
Antd have built in form management and support complex usage. It might seem overwhelming and hard to work with it for beginner or antd first time user. Here are some notes I tried to collect for my own future reference.
Preparations / Basics
- Wrap the whole form with
Form
(opens in a new tab) component. - Create form hook through
Form.useForm
:
const [form] = Form.useForm()
- Make sure to wrap each fields with
Form.Item
and definename
(similar concept likereact-hook-form
orformik
).
Things to Aware with Form
- Attach
form
state toForm
. - Define
initialValues
with state / immutable, not normal object. Why? Turns out anything passed toinitialValues
is prone to be unstable / becomes mutable. I tried to work around it with making sure passing state into it as state is immutable. This must be awared especially after switching back and forth between pages. Form
provideonFinish
that will only be triggered when submit and validation is success.Form
provideonFailure
that will be triggered when submit and validation is not passing.Form.Item
providerules
to define field validation.
Things to Aware with Inputs
Input, Select, NumberInput
- For general purpose inputs, use
Input
component. - For numeric inputs and expecting form state to also receive number, use
NumberInput
component. - For formatted number input, use
NumericInput
ofreact-number-format
and set customInput prop asInput
. - For switch toggle input, use
valuePropName="checked"
on theForm.Item
wrapper of the switch.
Working with Array fields
Form.List
can be used for array property / attribute of the form shape.Form.List
provide render function children:(fields, { add, remove, move }) => React.ReactNode
- We can combine
Form.List
withTable
and passfields
as Table'sdataSource
.