Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

399
Views
How to use Switch input in antd form?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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>;
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!