Issue
I'm new to Typescript and can't figure out how to type this situation.
I'm writing a custom hook and trying to create a callback ref.
My problem is that this function sets the ref's current
, and returns nothing, but since I use it as a ref, typescript yells at me Property 'current' is missing in type '(node: any) => void' but required in type 'RefObject<HTMLDivElement>'
.
Thank you in advance.
This is the code:
import React, {useCallback, useRef} from 'react'
const useCustom = (): [RefObject<HTMLDivElement>] => {
const ref = useRef<HTMLDivElement | null>(null)
const setRef = useCallback(node => {
....
ref.current = node
}, [])
return [setRef]
}
const SomeComp = () => {
const [ref] = useCustom()
return <div ref={ref}>Text</div>
}
Solution
The problem is you said the return value of useCustom
would be RefObject<HTMLDivElement>
, but returned (node: HTMLDivElement) => void
.
Your custom hook should return 2 values: one for setting the ref value, the other for the ref itself. So it will look like useState
hook:
const useCustom = (): [
RefObject<HTMLDivElement>,
(node: HTMLDivElement) => void
] => {
const ref = useRef<HTMLDivElement | null>(null);
const setRef = useCallback((node) => {
ref.current = node;
}, []);
return [ref, setRef];
};
Answered By - Diyorbek Sadullaev
Answer Checked By - - Marie Seifert (ReactFix Admin)