Reputation: 607
I have forwarded ref using React forwardRef
below is my code:
interface PropsDummy {}
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
console.log(ref.current);
}
but why this causing typescript error?
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'
but if I use aliasing that current object works great without typescript error
interface PropsDummy {}
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
const myRef = ref as React.RefObject<HTMLInputElement>;
console.log(myRef.current);
}
how to get current object without typescript error?
thanks
Upvotes: 7
Views: 4941
Reputation: 43234
The reason it doesn't work is because the type for ForwardedRef
is defined as:
type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null;
Or in this particular case:
((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>
Attempting to just access .current
, without doing some type checking won't work because as you can see, the ref
could be a function and functions do not have such a property (current
).
It worked when you cast the object to your expected type, but note that refs can be either a function or an object (or null!), so you should be checking for this before attempting to access the current
property.
This should work:
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, forwardedRef) => {
if (forwardedRef != null && typeof forwardedRef !== 'function') {
console.log(forwardedRef.current);
}
return (
<div className="App" ref={forwardedRef}>
<h1>Hello there</h1>
</div>
);
});
Upvotes: 15