React - New Context API not working with Class.contextType, but works with Context.Consumer
Asked Answered
C

1

7

I'm trying out the new context API using a HOC that returns a wrapped component. It doesn't work when I use the Class.contextType = Context approach:

return function myHOC(WrappedComponent) {
  class HOC extends React.Component {
    // static contextType = MyContext;

    render() {
      console.log(this.context);  // HERE, this logs `{}`

      // ..do stuff
      return <WrappedComponent {...this.props} />
    }
  }
  HOC.contextType = MyContext;

  return HOC;
};

However, I made the same code but using <MyContext.Consumer> and it worked fine:

return function myHOC(WrappedComponent) {
  const HOC = (props) => (
    <MyContext.Consumer>
      {(context) => {
        console.log(context);  // HERE, correct values

        return <WrappedComponent {...props} /> 
      }}
    </MyContext.Consumer>
  );

  return HOC;
};

Am I not seeing something here?

Cordillera answered 1/11, 2018 at 22:13 Comment(1)
For anyone else like me searching for the difference between Class.contextType and Context.Consumer that got redirected to this question, here's an answer: #54284009Caboodle
C
6

Turns out that even though I updated my react-scripts to 2.0, I had to update react to 16.6 (previously on 16.3) on my own.

I was under the impression react-scripts would also handle the react version. My bad, got confused there.

Cordillera answered 1/11, 2018 at 23:1 Comment(1)
I'm still getting {} for console.log(this.context). Updated the react-scripts version and react version. Can you help me with itJustinjustina

© 2022 - 2024 — McMap. All rights reserved.