Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 863
Softwareddy Avatar asked Jan 01 '26 01:01

Softwareddy


1 Answers

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

like image 170
max taldykin Avatar answered Jan 03 '26 14:01

max taldykin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!