I have a group of 4 radio buttons and I need to get the value of the selected button. I should make sure that the user has selected one of the radio buttons. Here is how I'm trying to do it:
export const ReportClass = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState() {
return {
reason: "",
}
},
setError(id, msg) {
const err = this.state.errors;
err[id] = msg;
this.setState({errors: this.state.errors});
},
sendReport(event) {
event.preventDefault();
console.log(this.state.reason);
console.log(this.state.reason.value);
if (!this.state.reason) {
this.setError('reason', "Please choose one");
return;
}
},
render: function() {
return (
<div>
<form className="form-h" onSubmit={this.sendReport}>
<label forHtml='first'> first radio button </label>
<input ref='first' name='reason' type='radio' value='first' checkedLink={this.linkState('reason')} />
<label forHtml='second'> second radio button </label>
<input ref='second' name='reason' type='radio' value='second' checkedLink={this.linkState('reason')} />
<label forHtml='third'> third radio button</label>
<input ref='third' name='reason' type='radio' value='third' checkedLink={this.linkState('reason')} />
<label forHtml='forth'> forth radio button </label>
<input ref='forth' name='reason' type='radio' value='forth' checkedLink={this.linkState('reason')} />
<div className="col-sm">
<button type="submit" className="btn" onClick={this.sendReport}> Send</button>
</div>
</form>
</div>
);
}
});
The console.log(this.state.reason)
returns true
when one of the buttons is selected and the second one, console.log(this.state.reason.value)
returns undefined
. So how can I get the value to know which one is chosed?
I think that checkedLink
binds checked-ness of an individual radio button to the state. Because you're binding multiple radio buttons to the same state key and radio buttons are mutually exclusive, the reason
will always be whichever change event fired last.
In my opinion, the best solution is to use react-radio-group
.
If you don't want an external dependency, an easy alternative is to not link state at all and set an onChange handler on every radio button that looks like this:
function onChange(e) {
if (e.target.selected) {
this.setState({ reason: e.target.value });
}
}
Now we don't need to worry about managing the checked-ness of each radio button, we just grab the reason whenever one is clicked. The downside to this is that it doesn't go both ways: if you set the reason on the state it wouldn't change which radio button is actually clicked.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments