Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS checkbox does not recognize the first toggle

I am just starting to check on and learn React js and trying some simple things with it. I have a problem with a simple checkbox - I created an event to listen for change and update it's state, but the problem is that the application does not recognize the first time that the checkbox is toggled. For example: - I render it with a default checked state - I click on it to uncheck it and the console logs true (should be false) - I click on it again to check it and the console logs true (this is now correct - from there on it returns the correct state.

Here's my sample code:

var CheckboxElement = React.createClass({

  handleChange: function(e) {

    this.setState({
      checked: !e.target.checked
    });

    console.log(this.state.checked);
  },

  getInitialState: function() {
    return {checked: false};
  },

  render: function() {
    return (
      <label><input type="checkbox" defaultChecked={this.state.checked} onChange={this.handleChange} />{this.props.optionVal}</label>
    )
  }
});

ReactDOM.render(
  <CheckboxElement optionVal="Test" />,
  document.getElementById('container')
);

And here is a jsFiddle with my code: https://jsfiddle.net/velio84/zro3x9eg/1/

You can check the browser's console to see the output.

Any help would be appreciated.

like image 749
Velichko Golev Avatar asked Sep 19 '26 04:09

Velichko Golev


1 Answers

In this case you don't need add !, because when you do first check e.target.checked value will be false(or true it depends on initial state) and state will have value true (!false === true) or false(!true === false), as I wrote it depends on initial value that you set for defaultChecked property

this.setState({
  checked: e.target.checked
});

Example

like image 95
Oleksandr T. Avatar answered Sep 20 '26 18:09

Oleksandr T.