Created
August 14, 2024 11:51
-
-
Save nikolovlazar/a270127f8a3271a1d6db289030048b57 to your computer and use it in GitHub Desktop.
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
const useFormField = () => { | |
const fieldContext = React.useContext(FormFieldContext) | |
const itemContext = React.useContext(FormItemContext) | |
const { getFieldState, formState } = useFormContext() // comes from from react-hook-form | |
const fieldState = getFieldState(fieldContext.name, formState) | |
if (!fieldContext) { | |
throw new Error('useFormField should be used within <FormField>') | |
} | |
const { id } = itemContext | |
return { | |
id, | |
name: fieldContext.name, | |
formItemId: `${id}-form-item`, | |
formDescriptionId: `${id}-form-item-description`, | |
formMessageId: `${id}-form-item-message`, | |
...fieldState, | |
} | |
} | |
const FormMessage = React.forwardRef< | |
HTMLParagraphElement, | |
React.HTMLAttributes<HTMLParagraphElement> | |
>(({ className, children, ...props }, ref) => { | |
const { error, formMessageId } = useFormField() | |
const body = error ? String(error?.message) : children | |
if (!body) { | |
return null | |
} | |
return ( | |
<p | |
ref={ref} | |
id={formMessageId} | |
className={cn('text-[0.8rem] font-medium text-destructive', className)} | |
{...props} | |
> | |
{body} | |
</p> | |
) | |
}) | |
FormMessage.displayName = 'FormMessage' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment