Do you want to request a feature or report a bug? feature
What is the current behavior? Using Component.contextType, this.context keeps null in class component's constructor.
What is the expected behavior?
this.context can be obtained in constructorthis.context cannot be used in constructor.Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? React 16.6 (older React doesn't have Component.contextType) in Chrome 70 (Windows 7)
Hm. Yea. This is a bug I think. It should probably be allowed.
Want to send a failing unit test and/or fix?
@maisumakun how are you calling super in the constructor? If you pass context to super it's accessible as expected.
https://codesandbox.io/s/l47jw5ryyz
class App extends React.Component {
static contextType = Context
constructor(props, context) {
super(props, context)
// this.context now works
}
This seems consistent with this.props. If you don't pass props to super you cannot access this.props in the constructor. Should this.context work differently?
@aweary Oh, thanks!
constructor(props, context) reminded me a code for legacy Context API, but necessary for contextType too. (this should be documented anywhere)
Please feel free to send a documentation PR to section about using contextType.
https://github.com/reactjs/rfcs
Most helpful comment
@maisumakun how are you calling
superin theconstructor? If you passcontexttosuperit's accessible as expected.https://codesandbox.io/s/l47jw5ryyz
This seems consistent with
this.props. If you don't passpropstosuperyou cannot accessthis.propsin the constructor. Shouldthis.contextwork differently?