Samat Zhetibaev
Samat Zhetibaev

Reputation: 600

React controlled checkbox (toggle) on props.

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:

  1. It looks unchecked, even if props equal to value={true}
  2. By clicking on this toggle it changes, but it shouldn't. I mean, if I put the prop 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

Answers (1)

Crysfel
Crysfel

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

Related Questions