Home > Enterprise >  Using focus on useRef is throwing the error: "property 'focus' does not exist on type
Using focus on useRef is throwing the error: "property 'focus' does not exist on type

Time:06-30

  const textInputRef = useRef();
  useEffect(() => {
    if (textInputRef && textInputRef.current) {
      textInputRef.current?.focus(); // property 'focus' does not exist on type 'never' 
    }
  }, []);

  return (
      <input ref={textInputRef} />
  )

The textInputRef.current?.focus() line is throwing property 'focus' does not exist on type 'never'

I'm on React 16.13.1, typescript 4.0.2 using hooks and function components

CodePudding user response:

The useRef needs a type passed to it. This is the type of the value it's expected to contain. Typescript can't crawl your code to see where the ref is used and figure out the type from that. You have to provide it when there is no default value.

In your case that would be:

const textInputRef = useRef<HTMLInputElement>(null);

See playground

  • Related