DEV Community

fazuelinton
fazuelinton

Posted on

Chakra checkbox and react-hook-form

My goal was to create a list of checkboxes with fixed values i.e. Nuts, Gluten, Dairy, etc.

screenshot of a list of checkboxes

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';
Enter fullscreen mode Exit fullscreen mode

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>
      )}
    />
  );
});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)