user967451
user967451

Reputation:

How to resolve these TypeScript errors when using React refs?

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?

Upvotes: 2

Views: 2029

Answers (1)

itsanewabstract
itsanewabstract

Reputation: 1036

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';
}

Upvotes: 3

Related Questions