Below is a simple react component with initial state of checkbox as false.
I am trying to change it dynamically using setState(). It does not work.
Here is my code:
var Hello = React.createClass({
getInitialState: function(){
return {
checked : this.props.checked.toString() === "false" ? false : true
};
},
render: function() {
console.log("rendering==");
return <div><input type = "checkbox" defaultChecked = {this.state.checked}/></div>;
}
});
var compRef = React.render(<Hello checked = "false" />, document.body);
Trying to change state after rendering the component
setTimeout(function(){
compRef.setState({checked: true})
},3000);
I am unable to change the checkbox state using setState.
Here is a fiddle
By providing defaultChecked instead of checked you are creating uncontrolled component.
Uncontrolled means that you can't control it by changing defaultChecked.
To change checkbox's state from code, you need to provide checked for it.
Here is updated fiddle: http://jsfiddle.net/p4ps7nob/
The other thing to consider is: Props in getInitialState Is an Anti-Pattern
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