Ref object is possibly undefined TypeScript React

useRef() returns an object with a current property, which contains the object you actually care about. And before the first render is complete, that current property will be null. This means the type of that ref is:

{ current: WhateverTypeYouCareAbout | null }

And that means you have to handle null as a possible value of the current property. But the ref object itself will always exist, it’s just that its current property may be null.

I would simply store the current value of your ref in a variable, test that existence, and then use it.

  useEffect(() => {
    const inputHasContentClassName="input--has-value";
    const inputElement = inputValue.current;        

    if (inputElement && inputElement.value.length > 0) {
      inputElement.classList.add(inputHasContentClassName);
    } else {
      inputElement.classList.remove(inputHasContentClassName);
    }
  }, [inputValue]);

You can also tell the TypeScript compiler the type of your ref (in this case HTMLInputElement) by doing the following:

const myRef = useRef<HTMLInputElement>();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)