I came of with a solution for pre checked radio button based on JSON data but I think the code can be improved. Or there should be a better way to implement it. The data is structure in following way:
{
radioA: 'Radio A',
radioB: 'Radio B',
radioC: 'Radio C',
selected: 'Radio A'
}
Not sure if this is the best way to do it. The data structure can be modified if needed.
Based on the data provided I am rendering radio button with one of them pre-selected. Following is what I have.
var App = React.createClass({
getInitialState: function(){
return {
radioA: 'Radio A',
radioB: 'Radio B',
radioC: 'Radio C',
selected: 'Radio A'
}
},
render: function(){
return(
<div>
{Object.keys(this.state).map(function(key) {
// Not displaying the selected data
if(key !== 'selected'){
// Checked radio button
if(this.state[key] == this.state['selected']){
return(
<div>
<label className="radio-inline" key={key} htmlFor={key}>
<input id={key} type="radio" checked value={key} /> {this.state[key]}
</label>
</div>
);
}
else{
return(
<div>
<label className="radio-inline" key={key} htmlFor={key}>
<input id={key} type="radio" value={key} /> {this.state[key]}
</label>
</div>
);
}
}
}, this)}
</div>
);
}
});
React.render(<App />, document.getElementById('container'));
The code is set up following jsfiddle.com https://jsfiddle.net/rexonms/2x7ey2L5/
Is there a better solution to implement this? Thanks in advance