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>
);
};
CodePudding user response:
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.
CodePudding user response:
Actually you could rewrite your input as follows
<input
type="checkbox"
name={id}
disabled={disabled}
checked={!!checked}
onChange={
(e)=>onChange(e.target.checked)
}
/>