javascriptreactjsjsxantdreact-props

Switch component is not working after switching from Checkbox


I was using Ant Design Checkbox earlier to check and publish the comments and it was working fine with no errors.

<Checkbox
  key={record.id}
  checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false}
  onChange={(e) => Update(e.target.checked, record)}
/> 

I want to use Switch instead.

<Switch
  key={record.id}
  checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false}
  onChange={(e) => Update(e.target.checked, record)}
/> 

I am getting error:

cannot read properties of undefined (reading 'checked)

I want Switch to work.


Solution

  • The onChange prop callback for the Switch component takes two arguments. The first is the current checked value and the second is the onChange event object.

    See the Switch component API:

    Property Description Type
    onChange Trigger when the checked state is changing function(checked: boolean, event: Event)

    Compared to the CheckBox component API:

    Property Description Type
    onChange The callback function that is triggered when the state changes (e: CheckboxChangeEvent) => void

    Update to use the first argument, checked:

    <Switch
      key={record.id}
      checked={Publish[record?.id]?.ispublish == 'true'}
      onChange={(checked) => Update(checked, record)}
    />