0

Suppose, I have two separate components X and Y, where X is a dependency in Y(not a direct child in the project). Is it possible to access the context of Y in X?

ex:

<Y.Provider value={key: 'val'}>
   <X />
</Y.Provider>

X is a separate project want to access Y's context, how can it be done? Can I import the context of Y in X and use it? Y is totally a separate(unknown until X is used as a dependency in Y) component?

Benison
  • 157
  • 1
  • 2
  • 17

1 Answers1

0

If you want to access some parent variable, the parent has to pass it as a prop.

Y could pass the props needed to its children

const Y = (props) => {
   const myVariable = 1

   return React.cloneElement(props.children, { context: myVariable })
}

Then X could access it via props.context.myVariable

lblenner
  • 372
  • 2
  • 14