From 9c732fc8654716a86e229b0d33d64a0288adff50 Mon Sep 17 00:00:00 2001 From: Lukas Weiss Date: Thu, 1 Aug 2024 08:08:56 +0200 Subject: [PATCH] make checkbox get correct checked state with array of values --- src/components/form/Checkbox.tsx | 7 ++++++- src/examples/form.templates.tsx | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/components/form/Checkbox.tsx b/src/components/form/Checkbox.tsx index da0f6648..a505d263 100644 --- a/src/components/form/Checkbox.tsx +++ b/src/components/form/Checkbox.tsx @@ -50,7 +50,12 @@ function CheckboxComponent( } = useTheme() const { register } = useFormContext() const { ref: fieldRef, ...field } = register(name) - const checked = useWatch({ name }) + const checkedValue = useWatch({ name }) + + // When there are multiple checkboxes with the same name but different values, checkedValue will be an array + const checked = Array.isArray(checkedValue) + ? Boolean(checkedValue.find((data) => data === props.value)) + : checkedValue const forwardedRef = useForwardedRef(ref) diff --git a/src/examples/form.templates.tsx b/src/examples/form.templates.tsx index 6ec75310..4b2dcd13 100644 --- a/src/examples/form.templates.tsx +++ b/src/examples/form.templates.tsx @@ -48,6 +48,7 @@ type FormData = { bio: string favProjectId: string | null serverValidationErrors: boolean + experiences: string[] } const defaultValues = { @@ -62,6 +63,7 @@ const defaultValues = { bio: 'John is a software engineer from Bolzano, Italy', favProjectId: '1', serverValidationErrors: false, + experiences: [], } const resolver = yupResolver( @@ -77,6 +79,7 @@ const resolver = yupResolver( bio: Yup.string(), favProjectId: Yup.string().nullable().required(), serverValidationErrors: Yup.boolean().required(), + experiences: Yup.array().of(Yup.string()), }) ) @@ -203,6 +206,30 @@ export function FormExampleTemplate({ useGetData={useGetData} paginationConfig={{ indexType: IndexType.ZERO_BASED }} /> +
+ + + +