javascriptreactjstypescriptantdant-design-pro

How can I have an antd checkbox checked when its value is falsy inside an antd formItem?


Currently, what I would like to do is "inverse" the behavior of the antd checkbox component. I want to have the checkbox unchecked when the value / initialValue of the antD formItem is false. This is my current code

<FormItem
  label="Include skills list in the search"
  labelCol={{ span: 24 }}
  initialValue={false}
  valuePropName="checked"
  name="ignoreSkills"
>
  <Checkbox value={false} defaultChecked={true}>Search on Skills</Checkbox>
</FormItem>

Setting the defaultChecked={true} works fine if the checkbox is OUTSIDE the formItem but when it's inside, everything just breaks.

Things I tried:

  1. Using the defaultChecked={true} alone. Doesn't work inside formItem
  2. Using the checked={true} property. Doesn't work inside formItem

Any idea how I can achieve this inside the antd formItem?


Solution

  • You can use getValueProps & getValueFromEvent prop to achieve inverse behaviour. getValueFromEvent function provides a custom handler how to extract value from a particular event i.e. for checkbox we need to get value form e.target.checked. So we pass valuePropName="checked". You can inverse the value of checkbox using this function. Using getValueProps, you can define how to get value from props.

    import { Checkbox, Form } from 'antd';
    
    const App = () => {
        return (
            <Form>
                <Form.Item
                    label='Include skills list in the search'
                    labelCol={{ span: 24 }}
                    valuePropName='checked'
                    name='ignoreSkills'
                    getValueProps={(value) => ({ checked: !value })}
                    getValueFromEvent={(e) => !e.target.checked}
                >
                    <Checkbox>Search on Skills</Checkbox>
                </Form.Item>
            </Form>
        );
    };
    
    export default App;