30

I have a component that uses a hook to set the input value into component state. I want to add a class when the input value is more than 0 characters in length, however I'm coming across an issue where TypeScript says my ref may be undefined.

I can't get rid of this error even if I check if the ref exists in the conditional that wraps the code to add the class. I'm not sure on the solution to this.

Error: Object is possibly 'undefined' on inputValue.current.classList.add(inputHasContentClassName);

import React, { useState, useEffect, useRef } from 'react';

const Component: React.FC = () => {
  const [inputValue, setInputValue] = useState('');
  const myRef = useRef();

  useEffect(() => {
    const inputHasContentClassName = 'input--has-value';

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

  function handleInputChange(e: React.FormEvent<HTMLInputElement>) {
    setInputValue(e.currentTarget.value);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    console.log('Submit form');
  }

  return (
    <>
      <section>
        <form onSubmit={handleSubmit}>
          <div>
            <input
              ref={myRef}
              onChange={handleInputChange}
              type="number"
            />
            <label>Input Label</label>
          </div>
          <button
            type="submit"
            disabled={inputValue.length === 0}
          >
            Submit
          </button>
        </form>
      </section>
    </>
  );
};

export default Component;
Antfish
  • 1,313
  • 2
  • 22
  • 41

1 Answers1

42

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>();
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • This resolves the initial error but I then get "classList" does not exist on type "never" even if I check for inputElement: `inputElement && inputElement.classList.add('classname')` – Antfish Jan 27 '20 at 10:10
  • Managed to solve it with `const inputElement = (myRef.current as unknown) as HTMLInputElement;` but this feels like a hack. – Antfish Jan 27 '20 at 11:55
  • 28
    Try `useRef();` – Alex Wayne Jan 27 '20 at 17:52
  • 3
    @AlexWayne - Thank you :-) ```useRef(); ``` – Nick Middleweek May 01 '20 at 12:59
  • Don't use ref as a hook dependency. This is not reliable, as mutating the ref won't trigger a re-render: https://stackoverflow.com/questions/60476155/is-it-safe-to-use-ref-current-as-useeffects-dependency-when-ref-points-to-a-dom – zavjs Aug 25 '21 at 18:39