how to use radio buttons in react class-based components
Using Radio Buttons in React Class-Based Components
If you want to create a form with radio buttons in a React class-based component, there are a few steps you need to follow.
Step 1: Import React and Component
import React, { Component } from 'react';
Step 2: Create a Class-Based Component
Create a class-based component by extending the Component
class.
class MyForm extends Component {
render() {
return (
<div>
{/* radio buttons will go here */}
</div>
);
}
}
Step 3: Create State for Radio Buttons
Create state for the radio buttons in the constructor method of the component.
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
selectedOption: ''
};
}
render() {
return (
<div>
{/* radio buttons will go here */}
</div>
);
}
}
In this example, we're setting the initial state of the selectedOption
property to an empty string.
Step 4: Create Radio Buttons
Create radio buttons inside the render method of the component.
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
selectedOption: ''
};
}
render() {
return (
<div>
<label>
<input
type="radio"
value="option1"
checked={this.state.selectedOption === 'option1'}
onChange={e => this.setState({ selectedOption: e.target.value })}
/>
Option 1
</label>
<label>
<input
type="radio"
value="option2"
checked={this.state.selectedOption === 'option2'}
onChange={e => this.setState({ selectedOption: e.target.value })}
/>
Option 2
</label>
</div>
);
}
}
In this example, we're using the checked
property to determine if a radio button is selected or not. We're also using the onChange
event to update the selectedOption
state when a radio button is selected.
Step 5: Add Submit Button
Add a submit button to the form.
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
selectedOption: ''
};
}
handleSubmit = event => {
event.preventDefault();
console.log(this.state.selectedOption);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>
<input
type="radio"
value="option1"
checked={this.state.selectedOption === 'option1'}
onChange={e => this.setState({ selectedOption: e.target.value })}
/>
Option 1
</label>
<label>
<input
type="radio"
value="option2"
checked={this.state.selectedOption === 'option2'}
onChange={e => this.setState({ selectedOption: e.target.value })}
/>
Option 2
</label>
</div>
<button type="submit">Submit</button>
</form>
);
}
}
In this example, we're adding a handleSubmit
method that will be called when the form is submitted. We're also wrapping our radio buttons in a form
element and adding a submit button.
That's it! Now you know how to use radio buttons in a React class-based component.