What type to use in useRef of iframe

Viewed 1222

I would like to avoid using a type of any and I can't find what type definition am I supposed to use for it:

const iframe = useRef<any>();

<iframe
    ref={iframe}
    sandbox='allow-scripts'
    srcDoc={rootHtml}
/>

So that later Typescript can recognize properties of iframe.current such as iframe.current.contentWindow and iframe.current.srcdoc,...

*Edit

If I try using HTMLIFrameElement as suggested I receive this error under the ref={iframe} saying:

Type 'MutableRefObject<HTMLIFrameElement | undefined>' is not >assignable to type 'LegacyRef | undefined'. Type 'MutableRefObject<HTMLIFrameElement | undefined>' is not >assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'HTMLIFrameElement | undefined' is not assignable to type >'HTMLIFrameElement | null'. Type 'undefined' is not assignable to type 'HTMLIFrameElement | >null'.ts(2322)

3 Answers

i'm very surprised hovering over the iframe ref prop in vscode didnt provide you with the type HTMLIFrameElement

EDIT: You will also need to default there to null as the element refs return the type or null and not undefined const f = useRef<HTMLIFrameElement>(null);

const iframe = useRef<HTMLIFrameElement>();

You can refer to this file to see other types in the future @types/react/global.d.ts

const iframe = useRef() as React.MutableRefObject<HTMLIFrameElement>;
Related