Reputation: 37
this is the class based radio group . I want to convert it to functional based radio group. how can i do it. the code is as below:
import React, { Component } from "react";
class Demo2 extends Component {
constructor() {
super();
this.state = {
name: "React"
};
this.onValueChange = this.onValueChange.bind(this);
this.formSubmit = this.formSubmit.bind(this);
}
onValueChange(event) {
this.setState({
selectedOption: event.target.value
});
}
formSubmit(event) {
event.preventDefault();
console.log(this.state.selectedOption)
}
render() {
return (
<form onSubmit={this.formSubmit}>
<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>
i want it working code for functional based component. i am new to react pls help.
Upvotes: 1
Views: 99
Reputation: 6736
Create a local state using React.useState
and change the template based on the updated state.
*Note:- this
operator is not needed for functional components.
And also you can return the template directly (no render method required)
Sample code:
import React, { useState } from "react";
import "./styles.css";
export default function Demo2() {
const [selectedOption, setSelectedOption] = useState("Male");
const onValueChange = (event) => {
setSelectedOption(event.target.value);
};
const formSubmit = (event) => {
event.preventDefault();
console.log(selectedOption);
};
return (
<form onSubmit={formSubmit}>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={selectedOption === "Male"}
onChange={onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={selectedOption === "Female"}
onChange={onValueChange}
/>
Female
</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
);
}
Working code - https://codesandbox.io/s/bold-platform-yr3l9?file=/src/App.js:0-1001
Upvotes: 1
Reputation: 21
import React, { useState } from "react";
function Demo2() {
const [checked, setChecked] = useState("Male");
const onValueChange = (event) => {
setChecked(event.target.value);
};
const formSubmit = (event) => {
event.preventDefault();
console.log(checked);
};
return (
<form onSubmit={formSubmit}>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={checked === "Male"}
onChange={onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={checked === "Female"}
onChange={onValueChange}
/>
Female
</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
);
}
Upvotes: 1