7

I am using react-hook-form with typescript and material-ui. I wanted to pass error message as a helperText to TextField. I have tried to do so using helperText={errors.email?.message} but typescript complains about this assignment.

Property 'email' does not exist on type 'NestDataObject<FormData>'.ts(2339)

I don't want to disable this rule from my .eslintrc file, because it may ignore other similar issues in my application, which may be desired at some places. What is the right way of assigning error message of react-hook-form as a helperText to material-ui components?

codesandbox link https://codesandbox.io/s/material-ui-react-form-hook-yi669

5
  • You don't have email defined in your FormData type. Commented Mar 14, 2020 at 2:40
  • Thats right, but what's the appropriate way of defining it? FormData coming from react-hook-form package. Commented Mar 14, 2020 at 2:43
  • Oh. Thanks @HunterMcMillen for hint. It's working now. Posting an answer. Commented Mar 14, 2020 at 2:47
  • No you defined it on line 5 of app.tsx: type FormData = { firstName: string; lastName: string; }; Commented Mar 14, 2020 at 2:47
  • Yes. updated my own sandbox, but then reverted and forked another one for answer. Thanks for help @HunterMcMillen. Commented Mar 14, 2020 at 2:53

1 Answer 1

4

Need to define a datatype for form data and pass it to 'useForm'.

type FormData = {
  email: string;
  password: string;
};

const { control, handleSubmit, errors } = useForm<FormData>();

Updated sandbox : https://codesandbox.io/s/material-ui-react-form-hook-answer-8cxc1

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you sir, after several hours without a solution, this works perfectly!
Hi @Mahesh, I used the above code but the error I get is " Property 'errors' does not exist on type 'UseFormReturn<FormData>'.ts(2339) "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.