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?
if statementto check ifcurrenthas a value or put this in auseEffectcurrentproperty can be undefined if the ref was created and used before assigning to an element. While anifcheck would work to make surecurrentis not undefined, a more elegant way to do it is by usingoptional-chainingwith version 3.7 and up. That would look something likeaudioElem.current?.style.border = '2px solid red';