Search code examples
javascriptreactjscomponentsradio-button

React - Can't Uncheck Radio Button


I don't know what I'm doing wrong, but I'm unable to uncheck current radio button or select other radio buttons.

Basically, I have a table of occupants' details and I want to be able to indicate one of them as primary. The values are stored and retrieved in an mysql db. I am relatively new to ReactJS.

var PrimaryOccupantInput = React.createClass({
    getInitialState: function()
    {
        return {
            primary_occupant: (!(this.props.primary_occupant == null || this.props.primary_occupant == false))
        };
    },
    primaryOccupantClicked: function()
    {
        this.setState({
            primary_occupant: this.state.primary_occupant
        });

        this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
    },
    render: function() {
        var is_primary = "";

        if(this.state.primary_occupant != null)
        {
            if(this.state.primary_occupant == true)
            {
                is_primary = <span className="text-success">Yes</span>;
            }
            else if(this.state.primary_occupant == false)
            {
                is_primary = <span className="text-danger">No</span>;
            }
            else
            {
                is_primary = this.state.primary_occupant;
            }
        }
        else
        {
            is_primary = <span className="text-muted"><em>undefined</em></span>;
        }

        return (
            <div>
                <input type="radio" id="primary_occupant" name="primary_occupant[]" ref="primaryOccupantCheckbox" checked={this.state.primary_occupant} onChange={this.primaryOccupantClicked} />&nbsp;|&nbsp;
                {is_primary}
            </div>
        );
    }
});

Solution

  • onChange handler primaryOccupantClicked is basically a toggle function, so you want to set state opposite to current state (i.e. !this.state.primary_occupant). This will fix the issue:

    primaryOccupantClicked: function()
        {
            this.setState({
                primary_occupant: !this.state.primary_occupant
            });
    
            this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
        },