Reputation: 600
I need to make a checkbox (toggle, like IOS) component, that doesn't use state and controls only by props. The current code looks like this:
export class Checkbox extends React.Component {
handleChange(event) {
this.props.onChange({value: event.target.value});
}
render() {
return (
<span>
<input class="ios_toggle" type="checkbox"
value={this.props.value}
disabled={this.props.disabled}
onChange={this.handleChange}
/>
</span>
);
}
}
I use it like this:
<Checkbox value={true} disabled={false} />
And it almost works, but:
value={true}
value={true}
, in theory it'll be the same, no matter what I do with it in browser? What did I miss?
Upvotes: 27
Views: 36853
Reputation: 8158
You need to use the checked
property instead of the value
. Try something like this instead:
export class Checkbox extends React.Component {
handleChange = () => {
this.props.onChange({ checked: !this.props.checked });
}
render() {
return (
<span>
<input class="ios_toggle" type="checkbox"
value={this.props.value}
disabled={this.props.disabled}
checked={this.props.checked}
onChange={this.handleChange}
/>
</span>
);
}
}
The value property can be anything, but the property that it's actually driving the toggle is called checked
Upvotes: 39