Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React controlled checkbox (toggle) on props.

Tags:

reactjs

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?

like image 719
Samat Zhetibaev Avatar asked Aug 10 '17 15:08

Samat Zhetibaev


People also ask

How do I toggle checkbox in Reactjs?

*/ 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.

How do I create a controlled checkbox in React?

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.

How do you handle toggle button in React?

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.


1 Answers

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

like image 84
Crysfel Avatar answered Sep 28 '22 08:09

Crysfel