I am working my way through a React Tutorial Book. At one point, the author showed me how to build a simple Form, which worked fine. Then, he proceeded to upgrade it to a 'React Hook Form'.
Everything work fine as per the instructions, until the very last line, where he says the following.
"Add a ref property to the input element in the Header component's JSX and set this to the register function from React Hook Form:"
At this exact moment, I run into the following error.
Type 'UseFormRegister<FormData>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
Type 'UseFormRegister<FormData>' is not assignable to type '(instance: HTMLInputElement | null) => void'.
Types of parameters 'name' and 'instance' are incompatible.
Type 'HTMLInputElement | null' is not assignable to type '"search"'.
Type 'null' is not assignable to type '"search"'. TS2322
103 | <form onSubmit={handleSubmit}>
104 | <input
> 105 | ref={register}
| ^
106 | name="search"
107 | type="text"
108 | placeholder="Search..."
The final code is available at this location - https://github.com/PacktPublishing/ASP.NET-Core-5-and-React-Second-Edition/blob/master/chapter-06/finish/frontend/src/Header.tsx
and I have compared my code to be identical, which I put below.
import React from 'react';
import { useSearchParams } from 'react-router-dom';
import { useForm } from 'react-hook-form';
type FormData = {
search: string;
};
export const Header = () => {
const { register } = useForm<FormData>();
const [searchParams] = useSearchParams();
const criteria = searchParams.get('criteria') || '';
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
ref={register}
name="search"
type="text"
placeholder="Search..."
defaultValue={criteria}
/>
</form>
</div>
);
};
I am still learning my way around React and TypeScript. I understand the error is something about a type mismatch. Specifically the 'search' cannot be null. But beyond that I have no clue how to fix this.
I have looked at the following existing questions. They all seem to be discussing this but not with React Hook Form.
Type 'null' is not assignable to type 'HTMLInputElement' ReactJs
useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>