Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Last active June 13, 2022 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/ec48989ace27d0e9470a73d23a437848 to your computer and use it in GitHub Desktop.
Save alfonmga/ec48989ace27d0e9470a73d23a437848 to your computer and use it in GitHub Desktop.
React Final Form + Chakra UI
import {
Checkbox,
FormControl,
FormControlProps,
FormErrorMessage,
// FormLabel,
InputProps,
} from "@chakra-ui/core"
import React, { PropsWithoutRef } from "react"
import { useField } from "react-final-form"
interface CheckboxFieldProps extends PropsWithoutRef<InputProps> {
/** Field name. */
name: string
/** Field label. */
label?: string
isDisabled?: boolean
outerProps?: PropsWithoutRef<FormControlProps>
}
const CheckboxField = React.forwardRef<HTMLInputElement, CheckboxFieldProps>(
({ name, label, placeholder, isDisabled, outerProps, ...props }, ref) => {
const {
input,
meta: { touched, error, submitError, submitting },
} = useField(name)
const normalizedError = Array.isArray(error) ? error.join(", ") : error || submitError
return (
<FormControl isInvalid={touched && normalizedError} isDisabled={isDisabled} {...outerProps}>
{/* {label && <FormLabel htmlFor={name}>{label}</FormLabel>} */}
<Checkbox {...input} id={name} {...props} ref={ref} isDisabled={submitting}>
{label}
</Checkbox>
<FormErrorMessage>{normalizedError}</FormErrorMessage>
</FormControl>
)
}
)
export default CheckboxField
export const CheckboxControl = ({ name, children }) => {
const {
input: { checked, value, ...input },
meta: { error, submitError, touched, invalid },
} = useField(name)
return (
<FormControl isInvalid={touched && invalid} my={4}>
<Checkbox isChecked={value} {...input} isInvalid={touched && invalid} my={4}>
{children}
</Checkbox>
<FormErrorMessage>{error || submitError}</FormErrorMessage>
</FormControl>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment