In this article, we will learn the basics of the radio button in the React.js application.
Prerequisites of React
- Familiarity with HTML and JavaScript.
- node.js installed
Create React Project
To create a React app, use the following command in the terminal.
Code
npx create-react-app matuiInstall Bootstrap
Now install Bootstrap by using the following command.
Code
npm install bootstrapNow, open the index.js file and add the import Bootstrap.
Code
import 'bootstrap/dist/css/bootstrap.min.css';Now right-click on the src folder, create a new component named 'radiobtndemo.js', and follow the code. In this file, we have created a class component in reactjs
JavaScript
import React, { Component } from "react";
class Radionbtn extends Component {
constructor() {
super();
this.state = {
name: "React"
};
this.onValueChange = this.onValueChange.bind(this);
}
onValueChange(event) {
this.setState({
selectedOption: event.target.value
});
}
formSubmit(event) {
event.preventDefault();
console.log(this.state.selectedOption)
}
onChangeValue(event) {
console.log(event.target.value);
}
render() {
return (
<div>
<div class="col-sm-12 btn btn-info"> How to Use Radio Button in React</div>
<form>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={this.state.selectedOption === "Male"}
onChange={this.onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={this.state.selectedOption === "Female"}
onChange={this.onValueChange}
/>
Female
</label>
</div>
<div>
Selected option is : {this.state.selectedOption}
</div>
</form>
</div>
);
}
}
export default Radionbtn;Now, import the radiobtndemo component in the src/App.js file.
JavaScript
import './App.css';
import Radionbtn from './radiobtndemo'
function App() {
return (
<div className="App">
<Radionbtn/>
</div>
);
}
export default App;Now, run the project using the 'npm start' command and check the result.

Summary
In this article, we learned the basics of the radio button in the React.js application.

Join the conversation! Your thoughts help the community grow.