To use radio buttons in React class-based component, we add inputs with type radio
.
For instance, we write
class App extends React.Component {
setGender(event) {
console.log(event.target.value);
}
render() {
return (
<div onChange={this.setGender.bind(this)}>
<input type="radio" value="MALE" name="gender"/> Male
<input type="radio" value="FEMALE" name="gender"/> Female
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
to add 2 radio buttons into the div.
We set the value
prop to set the value of event.target.valye
when we click on a radio button.
And then we set them to the same name
so we can pick on either one to pick a value.
Then we set onChange
to this.setGender.bind(this)
to get the checked value with event.target.value
when we pick a choice.