Categories
React Answers

How to fix ‘Type ‘null’ is not assignable to type ‘HTMLInputElement” error in React and TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *