I am trying to use useRef
with TypeScript but am having some trouble.
With my RefObject
(I assume) I need to access current
. (ie node.current
)
I have tried the following
const node: RefObject<HTMLElement> = useRef(null);
const node = useRef<HTMLElement | null>(null);
but when I go to set the ref
I am always told that X is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
return <div ref={ node }>{ children }</div>
Edit: this should not be restricted to any one type of element so not just HTMLDivElement | HTMLFormElement | HTMLInputElement
Edit: This should work as an example
import React, { useRef, RefObject } from 'react'; function Test() { // const node = useRef(null); // const node: RefObject<HTMLElement> = useRef(null); const node = useRef<HTMLElement | null>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={ node }></div> }
“Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLInputElement>'. Types of property 'current' are incompatible. Type 'undefined' is not assignable to type 'HTMLInputElement | null'. TS2322” Code Answer Type 'MutableRefObject ' is not assignable to type 'RefObject '. Types of property 'current' are incompatible.
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'. Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'. Types of property 'body' are incompatible. Type 'void' is not assignable to type 'BodyInit | null | undefined
Type '{}' is missing the following properties from type 'SVGSVGElement': contentScriptType, contentStyleType, currentScale, currentTranslate, and 270 more.ts (2322) index.d.ts (95, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & SvgIconProps '
Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'. Types of property 'current' are incompatible. Type 'HTMLDivElement | undefined' is not assignable to type 'HTMLDivElement | null'.
Just import React:
import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> }
I made an update. Use HTMLDivElement
as generic parameter instead of HTMLElement | null
. Also, contains
expects an argument.
UPDATE useRef
expects generic argument of DOM element type. You don't need to use | null
because RefObject
already knows that current
might be null.
See next type:
interface RefObject<T> { readonly current: T | null }
TS & React are smart enough to figure out that your ref might be null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With