I am working with react js and found a weird issue on radio button onChange
event binding.
My page opens a popup on button click where a new component bind inside that popup. In this new component I have created 2 radio buttons
and on change of that radio buttons I'm hide/show div. below is my code.
class component1 extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: true
};
}
handleChange = () => {
this.setState({
showComponent: !this.state.showComponent,
});
}
render() {
return(
<div>
<input type='radio' name='a' onChange={self.handleChange} defaultChecked/>
<input type='radio' name='a' onChange={self.handleChange}/>
{this.state.showComponent && (<div>Hide or show based on state change</div>)}
</div>
);
}
}
When I open the popup for the first time it works fine. Perhaps its behavior change after submitting form and popup close. When next time I open popup without parent page refresh, on first change of radio button it does not call handleChange
function. And from the second click it just works fine.
I think, onSubmit
I have called form.reset()
function on successful submission of form, which is creating problem. But i don't understand how to resolve this issue.
<input type='radio' name='a' onChange={this.handleChange} checked={!this.state.showComponent} />
<input type='radio' name='a' onChange={this.handleChange} checked={this.state.showComponent}/>
this will work find in a controlled way as opposed to reliance on event and defaultChecked