Bomber
Bomber

Reputation: 10957

ReactJs Checkbox - cannot uncheck

I am trying to set the checked prop of a checkbox using a state, updated code with handleChange function:

getInitialState: function() {
    return {
        selected:0,
        contactId: 0
    };
},

handleChange: function(e) {
    var id = this.state.contactId;

    console.log(e.target.checked);

    if (e.target.checked === true){

        console.log('selected');

        contactChannel.publish({
                    channel: "contact",
                    topic: "selectedContact",
                    data: {
                        id: [id]
                    }});

    } else{

        basketChannel.publish({
            channel: "basket",
            topic: "removePersonFromBasket",
            data: {
                id: [id]
            }
        });


        console.log('deselected flag');


    }
},
render: function() {

    var id = this.state.contactId;
    var isSelected = this.state.selected;

    console.log(isSelected);

    return (
        <div className="contact-selector">
            <input type="checkbox"
                   checked={isSelected}
                onChange={this.handleChange} />
        </div>
    );
}

However, once the checkbox is checked by default I cannot uncheck it, can anyone please tell me how to do this?

Many thanks

Upvotes: 4

Views: 10499

Answers (3)

Vishnu
Vishnu

Reputation: 12293

getInitialState: function() {
    return {
        selected:0,
        contactId: 0
    };
},

handleChange:function(event){
    this.setState({selected: !this.state.selected});
    isSelected = this.state.selected;

    console.log(isSelected);
}

render: function() {

    var id = this.state.contactId;
    var isSelected = this.state.selected;

    console.log(isSelected);

    return (
        <div className="contact-selector">
            <input type="checkbox"
                   checked={isSelected}
                onChange={this.handleChange} />
        </div>
    );
}

Upvotes: -1

udidu
udidu

Reputation: 8588

In the handleChange function you are always using the same value for the state of the check box but you need to reverse it.

add this to your handleChange function:

handleChange:function(event){
    this.setState({selected: !this.state.selected}); //look at the !NOT sign

}

Upvotes: 5

Salketer
Salketer

Reputation: 15711

The problem is because you return with the wrong variable. Changing {isSelected} with {this.state.selected} should work.

getInitialState: function() {
    return {
        selected:0,
        contactId: 0
    };
},


render: function() {

    var id = this.state.contactId;
    var isSelected = this.state.selected;

    console.log(isSelected);

    return (
        <div className="contact-selector">
            <input type="checkbox"
                   checked={this.state.selected}
                onChange={this.handleChange} />
        </div>
    );
}

Upvotes: 0

Related Questions