EDIT: this question was marked as a duplicate by some users. Not sure if they read it before doing so. If someone did, please clarify in which sense this is a duplicate.
I have a component for checkboxes:
class Checkbox extends Component {
onChange = (e) => {
if (this.props.input) {
this.props.input.onChange(e.target.checked);
} else if (this.props.onChange) {
this.props.onChange(e.target.checked, this.props.id);
}
};
render() {
const { input, value, className, label } = this.props;
let inputValue = (input && input.value) || value;
return (
<div className={'Checkbox' + (className ? ' Checkbox--' + className : '')}>
<input
className="Checkbox-input"
type="checkbox"
onChange={this.onChange}
checked={inputValue}
/>
<span className="Checkbox-helper" />
<span className="Checkbox-label" htmlFor="">
{label}
</span>
</div>
);
}
}
This component returns an error when the value changes.
Warning: A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
But if I replace:
let inputValue = (input && input.value) || value;
with
let inputValue = value;
if (input) {
inputValue = input.value;
}
Like so:
class Checkbox extends Component {
onChange = (e) => {
if (this.props.input) {
this.props.input.onChange(e.target.checked);
} else if (this.props.onChange) {
this.props.onChange(e.target.checked, this.props.id);
}
};
render() {
const { input, value, className, label } = this.props;
let inputValue = value;
if (input) {
inputValue = input.value;
}
return (
<div className={'Checkbox' + (className ? ' Checkbox--' + className : '')}>
<input
className="Checkbox-input"
type="checkbox"
onChange={this.onChange}
checked={inputValue}
/>
<span className="Checkbox-helper" />
<span className="Checkbox-label" htmlFor="">
{label}
</span>
</div>
);
}
}
It doesn't return any error. Why?