How to implement Root Error with Form components #2312
-
As the title said! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I guess i asked too early i figured how to do it with |
Beta Was this translation helpful? Give feedback.
-
Hey @billgun! I extended my Here's what I did: const FormRootError = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { errors } = useFormState()
const rootError = errors.root
if (!rootError) {
return null
}
return (
<p
ref={ref}
className={cn("text-destructive text-sm font-medium", className)}
{...props}
>
{rootError.message}
</p>
)
})
FormRootError.displayName = "FormRootError" I'll create a PR for this. |
Beta Was this translation helpful? Give feedback.
-
I modified the const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const { error: fieldError, ...fieldState } = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error('useFormField should be used within <FormField>');
}
let error = fieldError?.root ?? fieldError;
if (fieldError?.root) {
const { root, ...errors } = fieldError;
const hasErrors = Object.keys(errors).length > 0;
if (!hasErrors) {
error = undefined;
}
}
const { id } = itemContext;
return {
id,
error,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState
};
} It works well. |
Beta Was this translation helpful? Give feedback.
Hey @billgun!
I extended my
form.tsx
.Here's what I did:
I'll create a PR for this.