HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptreactMajor

useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthtmldivelementassignablelegacyrefnottypeuseref

Problem

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 = useRef(null);



  • const node = useRef(null);



but when I go to set the ref I am always told that X is not assignable to type 'LegacyRef | undefined'.

return { children }

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 = useRef(null);
    const node = useRef(null);

    if (
        node &&
        node.current &&
        node.current.contains()
    ){ console.log("current accessed")}

    return 
}

Solution

Just import React:
import React, { useRef } from 'react';

function Test() {
const node = useRef(null);

if (
node &&
node.current &&
node.current.contains()
){ console.log("current accessed")}

return
}


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 {
readonly current: T | null
}


TS & React are smart enough to figure out that your ref might be null

Context

Stack Overflow Q#66963289, score: 69

Revisions (0)

No revisions yet.