I am trying to create a generic input field for radio button which i am gonna use in my project whenever i need radio button in reactjs so i want to know how to pass radio buttons dynamically so that the first element is checked by default and how to use the checked property in map function
render() {
var self = this;
return(
<div>
{
self.props.options.map(function(option){
return <label key={option[self.props.id]}><input type="radio" className={self.props.className}
checked={?????} key={option[self.props.id]}
onChange={self.props.onChange} value={option[self.props.name]} />{option[self.props.name]}</label>
})
}
</div>
);
}
options is my array of objects which i am passing to the map function
Any help will be very helpful..
Thanks in advance :)
I am trying to create a generic input field for radio button which i am gonna use in my project whenever i need radio button in reactjs so i want to know how to pass radio buttons dynamically so that the first element is checked by default and how to use the checked property in map function
render() {
var self = this;
return(
<div>
{
self.props.options.map(function(option){
return <label key={option[self.props.id]}><input type="radio" className={self.props.className}
checked={?????} key={option[self.props.id]}
onChange={self.props.onChange} value={option[self.props.name]} />{option[self.props.name]}</label>
})
}
</div>
);
}
options is my array of objects which i am passing to the map function
Any help will be very helpful..
Thanks in advance :)
Share Improve this question edited Feb 14, 2017 at 10:21 Shubham Khatri 282k58 gold badges430 silver badges411 bronze badges asked Feb 14, 2017 at 10:11 Saif Ali KhanSaif Ali Khan 8483 gold badges9 silver badges35 bronze badges2 Answers
Reset to default 6You need to use the state for this. Use this:
this.state={checked: 0}
onChange(i){
this.setState({
checked:index
});
}
render() {
return(
<div>
{
this.state.options.map((option,i)=>{
return <label key={option[this.props.id]}>
<input
type="radio"
className={this.props.className}
checked={this.state.checked == i? true: false}
key={option[this.props.id]}
onChange={this.onChange.bind(this,i)}
value={option[this.props.name]} />
{option[this.props.name]}
</label>
})
}
</div>
);
}
Check the working fiddle: https://jsfiddle/039eq8bx/
You can hold a state of checked index and init it to 0, and on your onchange function change it to the selected index.
something like :
<div>
{ self.state.options.map(function(option,i){
return <label key={option[self.props.id]}>
<input type="radio"
className={self.props.className}
checked={i==self.state.checkedIndex}
key={option[self.props.id]}
onChange={self.onChange.bind(this,i)}
value={option[self.props.name]}
/>
{option[self.props.name]}
</label>
})
}
</div>
and on your onchange function
onChange = function(i) {
this.setState({checkedIndex : i})
}