Using focus on useRef is throwing the error: "property 'focus' does not exist on type 'never'"
Asked Answered
K

1

6
  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

Kasten answered 29/6, 2022 at 17:46 Comment(1)
I copy your code test it is working fine.Elbert
M
12

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

Milton answered 29/6, 2022 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.