Reputation: 5510
I'm having trouble getting the React contextType
property that is part of the new React Context API. The documents say:
The contextType property on a class can be assigned a Context object created by React.createContext(). This lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.
Unless I've missed something, then, the following code should make this.context
available on the App
class:
import React from "react";
import ReactDOM from "react-dom";
const MyContext = React.createContext({
on: false
});
import "./styles.css";
class App extends React.Component {
render() {
console.log("context: ", this.context);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
App.contextType = MyContext;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
(Example here)
However, when this code runs, the log statement just prints an empty object. I expected it to print out the default state I provided to the React.createContext
function.
Can someone help me understand what is going on here?
Upvotes: 1
Views: 1062
Reputation: 3547
I think you need React >=16.6.0
for this feature.
I updated react in your codesandbox and it works for me: https://codesandbox.io/s/w66k2k8o5l
Upvotes: 3