const [isPublished, setIsPublished] = useState(false);
const handleRadio = (event: { currentTarget: { value: string } }) => {
const isPublished = event.currentTarget.value === 'true' ? true : false;
setValues({ isPublished });
};
const initialValues = {
code: '',
product: '',
checked: false,
jobCardNo: '',
datePicker1: '',
datePicker2: '',
serial: '',
technicalNo: '',
lineNo: '',
show: false,
};
const [values, setValues] = useState(initialValues);
const handleInput = (e: { target: { name: any; value: any } }) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
Here I am setting up multiple input fields in a single state. I want to update radio button checked in a single state object.Please let me how to do this in these situations
<div className="radio">
<input
type="radio"
value="true"
checked={values.checked === true}
onChange={handleRadio}
/>
Yes
<input
type="radio"
value="false"
checked={values.checked === false}
onChange={handleRadio}
/>
No
</div>
CodePudding user response:
const [values, setValues] = useState(initialValues);
const handleRadio = (event) => {
let value = event.target.value
let name = event.target.name
setValues({ ...input, [name]: value })
}
add a name in input for handleRadio
<input
type="radio"
value="true"
name="name here"
checked={values.checked === true}
onChange={handleRadio}
/>
CodePudding user response:
Here's some changes I've made please follow the link: https://codesandbox.io/s/modern-rain-857z8b?file=/src/App.js
I've just added name for radio inputs
and used one handleInput
handler.
Here's a code example:
const initialValues = {
code: "", product: "",
checked: "false",
jobCardNo: "",
datePicker1: "",
datePicker2: "",
serial: "",
technicalNo: "",
lineNo: "",
show: false
};
const [values, setValues] = useState(initialValues);
const handleInput = (e) => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
return (
<div className="radio">
<input
type="radio"
value="true"
name="checked"
checked={values.checked === "true"}
onChange={handleInput}
/>
Yes
<input
type="radio"
value="false"
name="checked"
checked={values.checked === "false"}
onChange={handleInput}
/>
No
</div>
)