Home > other >  TypeScript/React: what does the RefObject<HTMLElement> datatype refer to?
TypeScript/React: what does the RefObject<HTMLElement> datatype refer to?

Time:02-19

I'm quite new to React & TypeScript and need to write testcases for some Frontend code. In the DTO of the component I want to test, there is a props-attribute defined with "RefObject" as Datatype. Only thing I could find has been that it is probably related to the useRef hook, but I couldn't get any further. In order to test the component I need to define some sampledata for the props, which is a bit hard when I don't really know what kind of data is supposed to be passed in there. I'd be very grateful for an explanation and an example of the data to pass in, since there are more components to test that implement this datatype

CodePudding user response:

As you already assumed, a RefObject<T> is the return type of useRef<T>(). The type definition is as follows:

interface RefObject<T> {
  readonly current: T;
}

Most likely the component you're trying to test will set the current property of this property to an HTMLElement, as indicated by the given generic. This means in order to mock the prop you can just pass the following:

myProp={{ current: null } as RefObject<HTMLElement>}

You might need an additional cast to unknown or replace RefObject<HTMLElement> with RefObject<HTMLElement | null> in case TypeScript complains when doing it this way.

  • Related