When building a form with shadcn/ui, there are existing form error messages for a field, but there is no component to display the error message to form’s root.
Why display the root error as text?
Some people might prefer using a toast to show the root error, but I personally feel it’s better to display it as text in the form, allowing the user to read it without worrying that the error message will disappear. This approach also feels more consistent with how field error is displayed as a text in the form.
The Component
Below is the component that I used for displaying the root error message.
function FormRootMessage({ className, ...props }: React.ComponentProps<"p">) {
const { errors } = useFormState();
const rootError = errors.root;
if (!rootError) {
return null;
}
return (
<p
data-slot="form-message"
className={cn("text-destructive text-sm", className)}
{...props}
>
{rootError.message}
</p>
);
}ui/form.tsx