Search code examples
reactjsreact-contextuse-contextuse-refreact-ref

Cannot destructure ref property as it is undefined trying to use a multiple ref context


I want to make a ref context, using that context's refs in my sections and then consuming the context in my navbar to use intersectionObserver.

Trying to achieve this at first i created a context with every ref and then using the context in my about component.

The context looks like this:

import React, { createContext, useRef } from "react";

export const RefsContext = createContext();

export const RefsProvider = (props) => {
  const aboutRef = useRef();
  const shopRef = useRef();
  const customersRef = useRef();
  return (
    <RefsContext.Provider
      value={{
        aboutRef,
        shopRef,
        customersRef,
      }}
    >
      {props.children}
    </RefsContext.Provider>
  );
};

export default RefsProvider;

And this is how i consume that context in my about.js: First i import the context: import { RefsContext } from "../../../context/refsContext"; then i use it: const { aboutRef } = useContext(RefsContext); and here i use that ref to referenciate a section: <section className="about" id="about" ref={aboutRef}>

I get this error message Uncaught TypeError: Cannot destructure property 'aboutRef' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined. in about.js:10, this line: const { aboutRef } = useContext(RefsContext);


Solution

  • Looks like you forgot to wrap whatever component is using this in RefsProvider. Does that fix this problem?

    EDIT: To provide further context, if you use useContext inside a component that is not wrapped in the Provider for the context you are accessing, the value will be undefined. I suspect that is what is happening here.

    In order to fix this, you need to wrap the component in RefsProvider

    For example:

    <RefsProvider>
      <YourComponentThatUsesRefsContext />
    </RefsProvider>