Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React controlled radio buttons not being checked

I have a child component that receives props from a parent. In the child component it renders a couple radio buttons like this:

               <div>
                    <div className="radio">
                        <label>
                            <input
                                type="radio"
                                name="value"
                                onChange={this._handleInputChange}
                                value="1"
                                checked={this.props.value === "1"}
                            />
                            True
                        </label>
                    </div>
                    <div className="radio">
                        <label>
                            <input
                                type="radio"
                                name="value"
                                onChange={this._handleInputChange}
                                value="0"
                                checked={this.props.value === "0"}
                            />
                            False
                        </label>
                    </div>
                </div>

handleInputChange just calls a parent method like so:

_handleInputChange(e) {
    this.props.handleChange(e);
}

that will set the state of the parent component to the value selected in the radio buttons (i.e. "1" or "0"). The issue im having is that the checked conditionals return the correct props, but they function strangely. It almost seems like when the radio input receives a new prop value, it doesn't re render with checked. When the component first renders, the props.value is an empty string. When a user selects a radio button it changes the state of the parent component with _handleInputChange and then sends that value back down for the conditionals.

like image 596
Munsterberg Avatar asked Nov 15 '25 01:11

Munsterberg


1 Answers

Thanks to some of the help here and on IRC I figured out it was a preventDefault in my event handler. After removing that it worked perfectly!

like image 137
Munsterberg Avatar answered Nov 17 '25 20:11

Munsterberg



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!