I have a file App.js
, from which a React component is exported as default. Besides that, the same file exports a React Context.
When using the Context in a child component (using static contextType = Context
), I just get the following warning:
Warning: Versions defines an invalid contextType. contextType should point to the Context object returned by React.createContext(). However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.
this.context
is also undefined.
However, using the consumer in the render method works just fine:
<Context.Consumer>{({ name }) => <p>{name}</p>}</Context.Consumer>
To better understand the issue, here's an example: https://codesandbox.io/s/empty-wood-qzrk1?fontsize=14 (see the console for the warning).
What am I doing wrong?
The problem is that you have a cyclic dependency here between App.js and the child component version.js
To solve the problem, all you need to do is to move context creation into a separate file
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With