INTEGRATING CHAKRA-UI’S CHECKBOX COMPONENT WITH BLITZ AND REACT-FINAL-FORM

INTEGRATING CHAKRA-UI’S CHECKBOX COMPONENT WITH BLITZ AND REACT-FINAL-FORM

When using Chakra-UI’s components in a Blitzjs app with react-final-form, you need to forward refs to the underlying component. Here’s a suggestion on how to set up our own checkbox component that wraps Chakra-UI’s checkbox.

// File: app/core/components/CheckboxField.tsx

import { forwardRef, PropsWithoutRef, ComponentPropsWithoutRef } from "react"
import { useField, UseFieldConfig } from "react-final-form"
import { Checkbox, InputProps } from "@chakra-ui/react"
import { FormControl, FormLabel } from "@chakra-ui/form-control"

export interface CheckboxProps extends PropsWithoutRef<InputProps> {
  name: string
  label: string
  isDisabled?: boolean
  outerProps?: PropsWithoutRef<JSX.IntrinsicElements["div"]>
  labelProps?: ComponentPropsWithoutRef<"label">
  fieldProps?: UseFieldConfig<string>
}

export const CheckboxField = forwardRef<HTMLInputElement, CheckboxProps>(
  ({ name, label, outerProps, fieldProps, labelProps, ...props }, ref) => {
    const {
      input,
      meta: { touched, error, submitError, submitting },
    } = useField(name, {
      type: "checkbox",
      ...fieldProps,
    })

    const normalizedError = Array.isArray(error) ? error.join(", ") : error || submitError

    return (
      <FormControl {...outerProps}>
        <FormLabel {...labelProps}>
          <Checkbox defaultIsChecked={true} id={name} ref={ref} isDisabled={submitting} {...input}>
            {label}
          </Checkbox>
        </FormLabel>
        {touched && normalizedError && (
          <div role="alert" style={{ color: "red" }}>
            {normalizedError}
          </div>
        )}
      </FormControl>
    )
  }
)

export default CheckboxField

To use the checkbox component in your form:

// File: app/companies/components/CompanyForm.tsx

import { Form, FormProps } from "app/core/components/Form"
import CheckboxField from "app/core/components/CheckboxField"

export function CompanyForm<S extends z.ZodType<any, any>>(props: FormProps<S>) {
  return (
    <Form<S> {...props}>      
      <CheckboxField name="checkbox" label="checkbox" placeholder="Check me!" />            
    </Form>
  )
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: