Home > other >  using ant design switch inside Forms
using ant design switch inside Forms

Time:10-26

What's the correct way to use ant design switch inside, I could not get much from the official documentation. Switch-Ant Design

Here's how I am using it.

<Form form={form} layout="vertical">
  <Form.Item
    label="Description"
    name="description"
    rules={[{ required: true, message: 'Enter a description' }]}
  >
    <Input placeholder="Enter Description" />
  </Form.Item>

  <Form.Item name="switch" noStyle valuePropName="checked">
    <Switch checkedChildren="Yes" unCheckedChildren="No" />
    <span>Chargable</span>
  </Form.Item>

  <Button
    onClick={() => {
      form
        .validateFields()
        .then((values) => {
          form.resetFields()
          onCreate(values)
        })
        .catch((info) => {
          console.log('Validate Failed:', info)
        })
    }}
  >
    Save
  </Button>
</Form>

onCreate does no take the value from the switch, It does take it from the description

const onCreate = (values) => {}

CodePudding user response:

I guess your values are {description: "foo", switch: undefined}?

In my demo, switch demo, I add initialValue to Switch, so when I get values from the form, I get {description: "111", switch: true}.

I don't know whether this is what your mean.

CodePudding user response:

I was able to fix it but doing the following.

<td>
  <Form.Item valuePropName="checked" name="status" noStyle>
    <Switch checkedChildren="Yes" unCheckedChildren="No" />
  </Form.Item>
  <span className="ml-2">Status Enabled</span>
</td>
  • Related