Last active
June 13, 2022 16:06
-
-
Save alfonmga/ec48989ace27d0e9470a73d23a437848 to your computer and use it in GitHub Desktop.
React Final Form + Chakra UI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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