Home > Net >  Type 'undefined' is not assignable to type 'RefObject<HTMLDivElement | undefined&g
Type 'undefined' is not assignable to type 'RefObject<HTMLDivElement | undefined&g

Time:09-01

I have a tsx file where the code is like below:

interface CommandProps {
    otherStuff: string;
    commandContainerRef: React.RefObject<HTMLDivElement | undefined>;
}

const getComponentProps = (): CommandProps => {
    return {
        otherStuff: 'stuff',
        commandContainerRef: undefined,
    };
};

.....

It gave me the error:

Type 'undefined' is not assignable to type 'RefObject<HTMLDivElement | undefined>'.

Then, I tired commandContainerRef: React.useRef(null), the above error is gone, but it gave me the eslint error below:

Error - React Hook "React.useRef" is called in function "getComponentProps" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use". (react-hooks/rules-of-hooks)

I am wondering how to address this issue. Thanks in advance!

CodePudding user response:

React.RefObject<T> is an interface with a read-only property named current of the given type T (or null), in this case CommandProps or undefined (or null).

So, if you want commandContainerRef returned from getComponentProps to be a React.RefObject to undefined this should work:

const getComponentProps = (): CommandProps => {
    return {
        otherStuff: 'stuff',
        commandContainerRef: { current: undefined },
    };
};

Or, depending on what your precise need is, you could alternatively change commandContainerRef to:

commandContainerRef: React.RefObject<HTMLDivElement> | undefined;

Then the getComponentProps implementation in the question should work.

  • Related