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