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 :)
The checked prop on each input conditionally checks if the selected state variable is equal to the input's value prop. If they are equal, the radio button gets checked. This is how we are able to set the default checked value of a radio button: We initialize the state variable to the value of the specific radio button.
The checked property sets or returns the checked state of a radio button. This property reflects the HTML checked attribute.
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck radio button dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.
Using a Radio Button Group with a FormThe onChangeValue() function gets called when the user selects the radio button from the group, and the value is updated into the component state. When the user is done with the selection, they may want to submit the form. The submit method is called formSubmit() .
You 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.net/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})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With