Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Typescript: Checkbox disabled using variable

console.log(disabled) is returning true but the checkbox is not getting disabled.

let disabled: boolean;

const GroupChange = (value) => {
   var index = dropdownItems.findIndex(item => item.group == value);
   ...

   disabled = dropdownItems[index].deactivated;
}

Form with the Checkbox:

<Form.Item label="Gruppe" name="group">
   <Select onChange={GroupChange}>
      {dropdownItems.map((item, index) => <Select.Option value={item.group} key={index}>{item.group}</Select.Option>)}
   </Select>
</Form.Item>

<Form.Item label="Aktiv" name="active" valuePropName="checked">
   <Checkbox disabled={disabled} /> //<- is always active 
</Form.Item>
...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In AntDesign, you use something called dependencies:

<Form.Item label="Gruppe" name="group">
   <Select>
      {dropdownItems.map((item, index) => <Select.Option value={item.group} key={index}>{item.group}</Select.Option>)}
   </Select>
</Form.Item>
<Form.Item dependencies={['group']}>
 {({getFieldValue}) => {
    const groupValue = getFieldValue('group')
    const isDisabled = dropdownItems.find(item => item.group === groupValue)?.deactivated
    return (
      <Form.Item label="Aktiv" name="active" valuePropName="checked">
        <Checkbox disabled={isDisabled} />
      </Form.Item>
    )
 }}
</Form.Item>

You render a Form.Item with a dependencies prop. The child is a function that gets form methods as an argument and gets called whenever the values of the dependencies change.

You DO NOT need, onGroupChange anymore.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading