Danil Pobirsky
Danil Pobirsky

Reputation: 3

checkbox react components. onChange of a checkbox must be called from the current checked state

Please help me to Component React Checkbox.

Props that the component acceptsProps that the component accepts CheckBox

type CheckBoxProps = Omit<
  React.InputHTMLAttributes<HTMLInputElement>,
  'onChange'
> & {
    /** Called when the checkbox is clicked */
    onChange: (value: boolean) => void;
}

Simple checkbox

<Checkbox
  checked={checked}
  onChange={setChecked}
/>

Block checkbox

<CheckBox
  disabled
  checked={checked}
  onChange={setChecked}
/>

I did this, but I don't understand how onChange of a checkbox must be called from the current checked state?

export const CheckBox: React.FC<CheckBoxProps> = ({
  disabled,
  id,
  checked,
  onChange,
}) => {
  return (
    <div>
      <label htmlFor={id}>
        <input
            type="checkbox"
            name={id}
            disabled={disabled}
            checked={checked !== null ? checked : false}
            onChange={event => event.currentTarget.checked}
        />
      </label>
    </div>
  );
};

Upvotes: 0

Views: 1204

Answers (2)

Dazly Gonsalves
Dazly Gonsalves

Reputation: 201

Actually you could rewrite your input as follows

<input
     type="checkbox"
     name={id}
     disabled={disabled}
     checked={!!checked}
     onChange={
      (e)=>onChange(e.target.checked)
     }
/>

Upvotes: 1

harsimarriar96
harsimarriar96

Reputation: 323

You haven't passed proper value of the onChange event for the checkbox input element.

Getting the value for input type "checkbox"

<input type="checkbox" onChange={(event) => onChange(event.target.checked)}/>

Getting the value for input type "text" or any other input type.

<input type="text" onChange={(event) => onChange(event.target.value)}

In the code, you were only calling the onChange event and returning the value of event.currentTarget.checked to the same event.

You will have to call a callback function and return the value to one of it's arguments to pass it to the parent Component.

Upvotes: 0

Related Questions