2

I'm setting a ref and typing it like this:

  const audioElem = useRef<HTMLAudioElement>();

Then when I use it like this:

  <audio ref={audioElem}></audio>

It causes this error:

(JSX attribute) ClassAttributes.ref?: string | ((instance: HTMLAudioElement | null) => void) | React.RefObject

And used like this:

audioElem.current.style.border = '2px solid red';

Causes this error:

(property) MutableRefObject<HTMLAudioElement | undefined>.current: HTMLAudioElement | undefined Object is possibly 'undefined'.

How can I get rid of these errors?

2
  • 1
    Consider adding an if statement to check if current has a value or put this in a useEffect Commented Jun 25, 2020 at 0:33
  • 3
    what version of typescript are you using? the current property can be undefined if the ref was created and used before assigning to an element. While an if check would work to make sure current is not undefined, a more elegant way to do it is by using optional-chaining with version 3.7 and up. That would look something like audioElem.current?.style.border = '2px solid red'; Commented Jun 25, 2020 at 0:41

1 Answer 1

3

A ref can possibly be null in React. Typescript is complaining that you haven't accounted for this possibility.

To resolve the first issue, pass in null to useRef like this:

const audioElem = useRef<HTMLAudioElement>(null);

To resolve the second issue, add an if statement that checks for audioElem.current like this:

if(audioElem.current) {
    audioElem.current.style.border = '2px solid red';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just to add more info: this blog has a full explanation of this issue and more "tips" on how to use Typescript with React Hooks: fettblog.eu/typescript-react/hooks/#useref

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.