Reputation: 156
I am using react-formik
for form I have one issue with checkbox based condition, the check relation to another two fields if user checked the hidden fields are showing else it's hidden, the user unchecked the remaining two contains values, but I want if user unchecked all fields to empty.
My code:
Thanks for help
Upvotes: 1
Views: 2746
Reputation: 5497
when you want to control the value of one field based on the value of other field you can make use of the setFieldValue
provided by Formik.
The Field
components has a render prop which is a function and which helps us to access the setFieldValue
in its argument. Now with the setFieldValue
being accessible you can use it set the value of the dependent fields when the checkbox is checked or unChecked.
You need to render the Field component for your checkbox as below
<Field
name="airconditioning"
render={({ meta, form }) => {
return (
<Checkbox
checked={meta.value}
onChange={(e) => {
const { checked } = e.target;
if (!checked) {
form.setFieldValue("airconditioningType", "");
form.setFieldValue("airconditioningStarred", "");
}
form.setFieldValue("airconditioning", checked || "");
}}
name="checkedB"
color="primary"
/>
);
}}
/>
Upvotes: 1