For some reason, with React 18 and Typescript 5.x, I cannot seem to access the properties of a ref that is most definitely set and defined through a context wrapper. I have something like this:
Parent component with context
interface MyContextValues {
ref: LegacyRef<ExternalApi>
}
export const MyComponentContext = createContext<MyContextValues>({ref:null})
export const MyComponent = () => {
const ref = useRef<ExternalThing | null>(null);
useEffect(() => {
console.log(ref.current); // ok!
}, [ref]);
return (
<MyComponent.Provider> value={{ref}}
<SomeComponent ref={ref}/>
</MyComponent.Provider>);
}
export const useMyComponentContext<MyContextValues>(MyContext);
Child component
export const MyChildComponent = () => {
const { ref } = useMyComponentContext();
useEffect(() => {
// Property 'current' does not exist on type 'string | ((instance: ExternalThing | null) => void) | RefObject<ExternalThing >'.
// Property 'current' does not exist on type 'string'.ts(2339)
console.log(ref.current);
// But it actually logs out fine to the expected value...
}, [ref]);
return <div></div>
}
>Solution :
Try React.RefObject instead of React.LegacyRef