Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React typescript ref.current is possible null. Why?

In my react typescript app I have this code:

  const inputRef = React.useRef<HTMLInputElement>(null);
  const onIconClick = () => {
    if (inputRef.current) {
      setTimeout(() => inputRef.current.focus(), 0);
    }
  };

Typescript highlights inputRef.current.focus() with text:

const inputRef: React.RefObject<HTMLInputElement>
Object is possibly 'null'.ts(2531)

But I do "null checking"…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I also tried this construction:

  const inputRef = React.useRef<HTMLInputElement>(null) as MutableRefObject<HTMLDivElement>

But I got error when I tried to pass ref to child component.

>Solution :

The ref may have changed in between your checking of if (inputRef.current) { and the call to .focus(). Either do

setTimeout(() => {
    if (inputRef.current) {
        inputRef.current.focus();
    }
}, 0);

or, more concisely, use optional chaining.

setTimeout(() => {
    inputRef.current?.focus();
}, 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading