Softwareddy
Softwareddy

Reputation: 841

Unable to change state of checkbox dynamically using setState

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

Upvotes: 3

Views: 401

Answers (2)

max taldykin
max taldykin

Reputation: 12898

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

Upvotes: 3

PhilVarg
PhilVarg

Reputation: 4820

if you want to toggle the state of a checkbox input, you need to utilize checked with an onChange handler instead of using defaultChecked.

Upvotes: 1

Related Questions