Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting Context not working with contextType

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?

like image 363
Andreas Remdt Avatar asked Dec 23 '22 21:12

Andreas Remdt


1 Answers

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

like image 164
Shubham Khatri Avatar answered Jan 02 '23 01:01

Shubham Khatri