3

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.

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.