Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argument of type 'RefObject<HTMLDivElement>' is not assignable to parameter of type 'IDivPosition'

I am using Typescript with react. I create a separate file for my custom function as DivPosition.tsx

I am using useRef to pass the reference of the div element to my function, but I am getting an error while passing the argument.

const Home = () => {
    const divRef = useRef<HTMLDivElement>(null);
    const x = DivPosition(divRef);

    return (
        ...
    )
}

my DivPosition.tsx code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface IDivPosition{
    divRef: HTMLDivElement | null
}

export const DivPosition = ({divRef}: IDivPosition) => {

  useEffect(() => {
      console.log(divRef);
  });
    ...
  return x;
};

I am getting an error saying:
Argument of type ‘RefObject’ is not assignable to parameter of type ‘IDivPosition’.
Property ‘divRef’ is missing in type ‘RefObject’ but required in type ‘IDivPosition’

>Solution :

The return value of useRef is RefObject, type definition

/*
* convenience overload for refs given as a ref prop as they typically start with a null value
*
* Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type
* of the generic argument.
* @version 16.8.0
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
function useRef<T>(initialValue: T|null): RefObject<T>;

try:

import { MutableRefObject, useEffect, useRef } from 'react';

interface IDivPosition {
  divRef: RefObject<HTMLDivElement>;
}

export const useDivPosition = ({ divRef }: IDivPosition) => {
  useEffect(() => {
    console.log(divRef);
  });
  return null;
};

const Home = () => {
  const divRef = useRef<HTMLDivElement>(null);
  const x = useDivPosition({ divRef });

  return null;
};

package versions:

"react": "^16.14.0",
"@types/react": "^16.14.14",
"typescript": "^4.4.2"

Besides, please name the custom hooks starting with "use".

Do I have to name my custom Hooks starting with “use”? Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading