To fix ‘Type ‘null’ is not assignable to type ‘HTMLInputElement” error in React and TypeScript, we can create a type guard function.
Then we use that to check if the ref is an HTMLInputElement
.
For instance, we write
const isInputElement = (elem: HTMLElement | null): elem is HTMLInputElement => {
if (!elem) {
return false;
}
return elem.tagName === "INPUT";
};
if (isInputElement(textInput)) {
console.log(elem.value);
}
//...
<input
ref={textInput}
type="text"
placeholder="Search"
/>
to create the isInputElement
type guard.
Then we check if elem
is falsy and return false
if it is.
Otherwise we check if the tagName
of the elem
object if 'INPUT'
.
Then we check if the textInput
ref is an input element with isInputElement
.
And then we get the value
property.