Skip to content

Commit

Permalink
fix(history): [checkbox] prevent double select
Browse files Browse the repository at this point in the history
When clicking on checkbox label
it overrides whole field value
because we pass as field name as id to all checkboxes in group
This will generate unique id for each checkbox preventing this bug
from occuring

Signed-off-by: Danil Kostromin <[email protected]>
  • Loading branch information
Danil Kostromin committed Mar 28, 2024
1 parent 738c23d commit ab1d2ed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
18 changes: 12 additions & 6 deletions libs/shared/tailwind-ui/src/lib/checkbox/checkbox-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/* SPDX-FileCopyrightText: 2021-2023 OKTET Labs Ltd. */
import { CheckedState } from '@radix-ui/react-checkbox';
import { Control, FieldValues, Path, useController } from 'react-hook-form';
import { useId } from 'react';

import { Checkbox, CheckboxProps } from './checkbox';

Expand All @@ -14,10 +15,8 @@ export const CheckboxField = <T extends FieldValues>({
control,
...props
}: CheckboxFieldProps<T>) => {
const { field } = useController({
name: props.name,
control: control
});
const { field } = useController({ name: props.name, control: control });
const checkId = useId();

const isChecked = Array.isArray(field.value)
? field.value.includes(props.value)
Expand All @@ -30,15 +29,22 @@ export const CheckboxField = <T extends FieldValues>({
}

const set = new Set(field.value);
set.has(props.value) ? set.delete(props.value) : set.add(props.value);

if (set.has(props.value)) {
set.delete(props.value);
} else {
set.add(props.value);
}

field.onChange(Array.from(set));
};

const id = `${checkId}_${field.name}`;

return (
<Checkbox
{...props}
id={field.name}
id={id}
checked={isChecked}
onCheckedChange={handleChange}
ref={field.ref}
Expand Down
2 changes: 1 addition & 1 deletion libs/shared/tailwind-ui/src/lib/checkbox/checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ const BoxedCheckbox = forwardRef<HTMLButtonElement, BoxedCheckboxProps>(
<Icon name={iconName} size={iconSize} />
</RadixCheckbox.CheckboxIndicator>
<label
htmlFor={props.name}
htmlFor={props.id}
className="text-[0.75rem] font-medium leading-[0.875rem]"
>
{label}
Expand Down

0 comments on commit ab1d2ed

Please sign in to comment.