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?
*/ function Checkbox() { const handleChange = () => { console. log('The checkbox was toggled'); }; return ( <div> <input type="checkbox" onChange={handleChange}> </div> ); }; export {Checkbox}; What is this? The example above will log a message to the console when the checkbox is toggled.
Controlling the input checkbox As mentioned earlier, React recommends making our form elements a controlled field. To do this, we must add a component state to manage the user's input and then pass the state variable to the input. For checkbox input, we will assign the state to the input checked attribute.
You have to update the state via useState hook and import it at the top level. let [changeText, setChangeText] = useState(true); The text in the bracket and assigned to some value is called array destructing.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With