I'm having a surprisingly hard time setting a default option for a radio button component in React.
Here is my RadioToggle
component:
/** @jsx React.DOM */
var RadioToggle = React.createClass({
render: function () {
var self = this;
return (
<div className="RadioToggle">
{this.props.radioset.radios.map(function(radio, i){
return (
<label className="__option" key={i}>
<h3 className="__header">{radio.label}</h3>
{radio.checked ?
<input className="__input"
type="radio"
name={self.props.radioset.name}
value={radio.value}
defaultChecked />
: <input className="__input"
type="radio"
name={self.props.radioset.name}
value={radio.value} />
}
<span className="__label"></span>
</label>
)
})
}
</div>
);
}
});
module.exports = RadioToggle;
And here is how I'm creating the component:
<RadioToggle radioset={
{
name: "permission_level",
radios: [
{
label: "Parent",
value: 1,
checked: false
},
{
label: "Child",
value: 0,
checked: true
}
]}
}/>
The above code works, but we don't like generating almost identical code depending on the radio.checked
option.
The way the component is set up, I pass it a name and an array of radios to create, and for each object in the radios array use that data to create a radio button.
In other cases I've been able to conditionally set attributes by putting ternary statements as the value, like below, but that doesn't work here.
The problem with defaultChecked={radio.checked ? "checked" : ""}
is that even with the output becoming checked="checked"
on one radio button and checked
on the other, it makes both radio buttons checked by default, resulting in the last one actually being checked.
Again, the component above works, but I'm hoping someone with some more experience with React will have a cleaner way of doing it rather than generating almost identical elements except for that attribute.
map
as the second argument rather than usevar self = this
.this.props.radioset.radios.map(..., this);
. – Mandrill