Home > front end >  How to use Switch input in antd form?
How to use Switch input in antd form?

Time:02-17

I'm using Antd "version": "4.16.6", and we have Switch field in one of our forms:

<Form
  ref={registerForm}
  initialValues={{
  hasArchive: true
}}>
    <Form.Item name="hasArchive" label="Has Archive?" valuePropName="checked">
      <Switch defaultChecked />
    </Form.Item>
</Form>

but Switch doesn't change hasArchive value.

CodePudding user response:

These two components are working for me.

import React, { useState } from "react";
import { Form, Switch } from 'antd';

const Example1 = () => {
  const [isChecked, setIsChecked] = useState(false);
  const onFinish = (value) => {
    console.log(value)
  }
  return <Form
    name='example-form'
    onFinish={onFinish}
    initialValues={{
      isChecked
    }}
  >
    <Form.Item
      name='isChecked'
      valuePropName='checked'
    >
      <Switch onChange={setIsChecked} />
    </Form.Item>
  </Form>;
};

const Example2 = () => {
  const onFinish = (value) => {
    console.log(value)
  }
  return <Form
    name='example-form'
    onFinish={onFinish}
    initialValues={{
      isChecked: true
    }}
  >
    <Form.Item
      name='isChecked'
      valuePropName='checked'
    >
      <Switch />
    </Form.Item>
  </Form>;
};

CodePudding user response:

Use onChange attribute to listen to the switch toggle.

import { Switch } from 'antd';

function handleSwitchToggle(checked) {
  console.log(`switch to ${checked}`);
}

ReactDOM.render(<Switch defaultChecked onChange={handleSwitchToggle} />, mountNode);

ref: https://ant.design/components/switch/

To update the form values use the below code, just put initialValue attribute in Form.item

<Form.Item
        name="switch"
        label="Switch"
        valuePropName="checked"
        initialValue
>
        <Switch checkedChildren="YES" unCheckedChildren="NO" />
</Form.Item>

you can test the code in this playground with antd switch example https://codesandbox.io/s/xiao-yan-qi-ta-zu-jian-antd-4-17-0-alpha-7-forked-00zvbr?file=/index.js:518-691

  • Related