My goal was to create a list of checkboxes with fixed values i.e. Nuts, Gluten, Dairy, etc.
After fetching the data and wiring it up with react-hook-form here's what I did:
import the required packages from libs
import { Controller } from 'react-hook-form';
import {
Checkbox,
CheckboxGroup,
CheckboxProps,
FormControl,
forwardRef
} from '@chakra-ui/react';
create a new component CheckboxCustom
...
type CheckboxCustomProps = CheckboxProps & { control: any; name: string; children: ReactNode };
const CheckboxCustom = forwardRef<CheckboxCustomProps, 'input'>(({ children, ...rest }, ref) => {
rest.control;
return (
<Controller
name={rest.name}
control={rest.control}
render={({ field: { value } }) => (
<Checkbox ref={ref} isChecked={value} {...rest}>
{children}
</Checkbox>
)}
/>
);
});
use the custom component to render the checkboxes
<FormControl>
<CheckboxGroup>
<SimpleGrid columns={5}>
<CheckboxCustom control={control} {...register('noNuts')}> Nuts
</CheckboxCustom>
<CheckboxCustom control={control} {...register('noGluten')}> Gluten
</CheckboxCustom>
...
</SimpleGrid>
</CheckboxGroup>
</FormControl>
Top comments (0)