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

Cannot access ref from React context

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

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

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

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