1.whenever i click on radio button it call the handleOptionChange callback but not reflect the change in html. 2.but when i click twice on radio button it reflect the change
My question is why i need to click twice on radio buttons? Is am i doing anything wrong?
class CompleteProfile extends Component{
constructor(props){
super(props);
this.state = {
teacher_role:'subject'
};
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(event){
event.preventDefault();
let { name, value } = event.target;
this.setState( { [name]:value } );
}
render(){
let { teacher_role } = this.state;
console.log('teacher:',teacher_role);
return(
<Wrapper className="complete-profile">
<CustomContainer>
<Title>complete profile</Title>
<ProfileCard>
<Form noValidate>
<FormGroup>
<label>I want to enroll as:</label>
<label htmlFor="test">
<input id="test" type="radio" name="teacher_role" value="subject" checked={ teacher_role === 'subject' } onChange={ this.handleOptionChange } />
subject teacher
</label>
<label htmlFor="test1">
<input id="test1" type="radio" name="teacher_role" value="chapter" checked={ teacher_role === 'chapter' } onChange={ this.handleOptionChange } />
class teacher
</label>
<label htmlFor="test2">
<input id="test2" type="radio" name="teacher_role" value="both" checked={ teacher_role === 'both' } onChange={ this.handleOptionChange } />
both
</label>
</FormGroup>
</Form>
</ProfileCard>
</CustomContainer>
</Wrapper>
)
}
componentWillUpdate(nextProps){
}
componentDidUpdate(prevProps){
}
}
Radio buttons allow a user to select a single option among multiple options. You can set the Choice Value of each option, for each button, as well as group these buttons by giving them the same Group Name.
To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected.
Input Reset focus() Method The focus() method is used to give focus to a radio button. Tip: Use the blur() method to remove focus from a radio button.
remove event.preventDefault();
from your handleOptionChange
method
For others running into this problem, make sure you are not using the same name
property for multiple groups of radio buttons.
This can happen when mapping through an array and rendering a set of radio buttons for each array item. Avoid this issue by adding the index of the current array item to the radio button name.
Note that in this case there should be no need for preventDefault
in the handleOptionChange
method.
If you are like me and need to use event.preventDefault()
, for example to prevent the input from submitting. You can use event.stopPropagation()
instead.
see this issue comment explaining for more context
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