Skip to content

Commit

Permalink
make checkbox get correct checked state with array of values
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasvice committed Aug 1, 2024
1 parent 8e28d23 commit 9c732fc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/components/form/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
27 changes: 27 additions & 0 deletions src/examples/form.templates.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type FormData = {
bio: string
favProjectId: string | null
serverValidationErrors: boolean
experiences: string[]
}

const defaultValues = {
Expand All @@ -62,6 +63,7 @@ const defaultValues = {
bio: 'John is a software engineer from Bolzano, Italy',
favProjectId: '1',
serverValidationErrors: false,
experiences: [],
}

const resolver = yupResolver(
Expand All @@ -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()),
})
)

Expand Down Expand Up @@ -203,6 +206,30 @@ export function FormExampleTemplate({
useGetData={useGetData}
paginationConfig={{ indexType: IndexType.ZERO_BASED }}
/>
<FieldSet
label="Experience with"
fields={['experiences']}
indent={FieldSetIndent.labelAndChildren}
>
<Checkbox
name="experiences"
value="typescript"
label="TypeScript"
applyInputHeight
/>
<Checkbox
name="experiences"
value="react"
label="React"
applyInputHeight
/>
<Checkbox
name="experiences"
value="next"
label="Next"
applyInputHeight
/>
</FieldSet>
<FieldSet
label="Privacy"
fields={['privacy']}
Expand Down

0 comments on commit 9c732fc

Please sign in to comment.