Home > Enterprise >  React Typescript: Checkbox disabled using variable
React Typescript: Checkbox disabled using variable

Time:12-29

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>
...

CodePudding user response:

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.

  • Related