WildThing
WildThing

Reputation: 1285

using ant design switch inside Forms

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) => {}

Upvotes: 5

Views: 11314

Answers (3)

Mourad Qqch
Mourad Qqch

Reputation: 459

This is because you must only have one child inside a Form.Item component. Remove the span besides your Switch component and it will work.

Upvotes: 3

LeeKlaus
LeeKlaus

Reputation: 299

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.


or you can use like this

<Form.Item label="foo">         
  <Form.Item name="bar">           
    <Switch />         
  </Form.Item>         
  <span className="ant-form-text">Some text you want</span>       

</Form.Item>

Upvotes: 3

WildThing
WildThing

Reputation: 1285

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>

Upvotes: 8

Related Questions