What I have
I have an Ant Design 4 form with a checkbox in it:
const Example = ({ initialValues, onSave }) => { const [form] = Form.useForm(); useEffect(() => { form.resetFields(); }, [initialValues.isAccepted]); const onFinish = (values) => { console.log(values); onSave(values); }; const getInitialValues = useCallback(() => ({ isAccepted: initialValues.isAccepted || false, })); return ( <Form form={form} onFinish={onFinish} initialValues={getInitialValues()}> <Form.Item name="isAccepted"> <Checkbox>The company can use my data</Checkbox> </Form.Item> <Button type="primary" htmlType="submit">Save</Button> </Form> ); };
Problem
The checkbox is always unchecked even if it is true
inside initialValues
. Also, when I submit the form the values
variable always contains the value from initialValues
, it doesn’t registers that I changed (checked or unchecked) the checkbox.
Goal
I would like the initial value to be set properly from inititalValues
and get the current value of the checkbox in onFinish
.
Advertisement
Answer
tl;dr
Add valuePropName="checked"
to the Form.Item
component:
<Form.Item name="isAccepted" valuePropName="checked">
Explanation
A checkbox’s value is not stored in a value
attribute like for text inputs. Instead, it has a checked
attribute. You have to tell the Form.Item
component to set that attribute/prop by telling the prop’s name through valuePropName
.
The docs on Form.Item
describes this prop:
valuePropName
: Props of children node, for example, the prop of Switch is ‘checked’. This prop is an encapsulation ofgetValueProps
, which will be invalid after customizinggetValueProps
Later it describes how the wrapping happens:
After wrapped by
Form.Item
withname
property,value
(or other property defined byvaluePropName
)onChange
(or other property defined bytrigger
) props will be added to form controls, the flow of form data will be handled by Form…