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:
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'
CodePudding user response:
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.