-
Notifications
You must be signed in to change notification settings - Fork 16
Open
Description
Description
The ErrorMessage component supports not providing the errors prop. Errors are then fetched from the form context provided by a FormProvider. Omitting the error prop therefore gives no typescript-error. However, if you forget to provide the form context you get an un-handled TypeError: Cannot read properties of null (reading 'formState') causing nothing to be rendered on the screen.
Suggested fix
While this is a small issue it is also easy to improve the developer experience which in my opinion makes it worthwhile. I suggest the following patch, which I am happy to make a PR with:
diff --git i/src/ErrorMessage.tsx w/src/ErrorMessage.tsx
index 0196985..282961a 100644
--- i/src/ErrorMessage.tsx
+++ w/src/ErrorMessage.tsx
@@ -18,6 +18,10 @@ const ErrorMessage = <
...rest
}: Props<TFieldErrors, TAs>) => {
const methods = useFormContext();
+ if (!errors && !methods) {
+ throw Error('A FormProvider is required when omitting the errors prop.');
+ }
+
const error = get(errors || methods.formState.errors, name);
if (!error) {Minimal example to reproduce:
import { useForm } from "react-hook-form";
import { ErrorMessage } from "@hookform/error-message";
export default function App() {
const form = useForm<{ requiredField: string }>();
return (
// Forgot to add <FormProvider {...form}> here
<form>
<input
{...form.register("requiredField", {
required: "This field is required",
})}
/>
<ErrorMessage
name="requiredField"
render={({ message }) => <span>{message}</span>}
/>
</form>
);
}martinostvik, pkarczmarczyk94, olavgu and sighmun
Metadata
Metadata
Assignees
Labels
No labels