React: Cannot be used new contextType API in constructor?

Created on 24 Oct 2018  路  5Comments  路  Source: facebook/react

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 constructor
  • if implementing of the feature is inappropriate, write in documentations that this.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)

Most helpful comment

@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?

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings