Reputation: 12054
I'm trying to create a yes-no radio buttons with react but using only one state. Thus, I have something like this :
<label className="radio-inline">
<input
type="radio"
name={this.props.nameYes}
defaultChecked={this.props.state}
onChange={this.props.onChangeEmailNotifications}
value="yes"/>Yes
</label>
<label className="radio-inline">
<input
type="radio"
name={this.props.nameNo}
defaultChecked={!this.props.state}
onChange={this.props.onChangeEmailNotifications}
value="no"/>No
</label>
The state I pass with a parent component is set to true.
This onChange function is :
changeCheckboxState: function(event){
var chcName = event.target.name;
switch(chcName){
case "chcEmailNotificationsYes":
this.state.user.emailNotifications = event.target.checked;
this.setState({user: this.state.user});
console.log('checkbox ' + chcName + " state je : ", this.state.user.emailNotifications);
break;
case "chcEmailNotificationsNo":
this.state.user.emailNotifications = !event.target.checked;
this.setState({user: this.state.user});
console.log('checkbox ' + chcName + " state je : ", this.state.user.emailNotifications);
break;
default:
console.log("Sad smo u default");
}
}
But those radio buttons aren't working. In console log I see that the state is changed, but it doesn't have effect on the radio buttons.
And is there any way to set the state to null at the beginning, that buttons aren't checked?
Upvotes: 0
Views: 1104
Reputation: 615
I believe that your radio buttons are not being checked as React is expecting a click event (see https://facebook.github.io/react/docs/forms.html#potential-issues-with-checkboxes-and-radio-buttons), according to that link you'll need to remove the call to preventDefault. Your syntax also appears incorrect to me -
This is a prop not state (If this is correct I'd suggest using a different property name)
defaultChecked={this.props.state}
It should look something like this
defaultChecked={this.state.xxxx}
With regards to the setting of state, you can use getInitialState
to set the state to null
, this can then be updated onChange
or using a click method.
Your use of defaultChecked
appears correct.
Upvotes: 0