Skip to content
Advertisement

Antd 4 Checkbox doesn’t have value after form submit

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 of getValueProps, which will be invalid after customizing getValueProps

Later it describes how the wrapping happens:

After wrapped by Form.Item with name property, value (or other property defined by valuePropName) onChange (or other property defined by trigger) props will be added to form controls, the flow of form data will be handled by Form…

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement