1

I'm trying to migrate to new version of React(16.3.2) and ran into a problem with getting access to context in new context API.

I have a Provider component

Provide.js

export const Context = React.createContext();

export default class Provider extends Component {
constructor(props) {
    super(props);

    this.state = {
      selection: new Selection({
        defaultSelection: props.defaultSelection,
        onChange: props.onChange,
      }),
    };
  }
}

render() {
    const { children } = this.props;

    return (
      <Context.Provider value={this.state}>
        {children}
      </Context.Provider>
    );
  }

And in the Consumer component I can get acces to context in render method.

import { Context } from '../Provider';

export default class Consumer extends Component {
  constructor(props, context) {
    super(props, context);

   // `this.context` is empty Object
    if (this.context.selection) {
      context.selection.register(props.tabFor);
    }

    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    // `this.context` is empty Object
    if (this.context.selection) {
      this.context.selection.subscribe(this.update);
    }
  }

  handleClick(event) {
    // `this.context` is undefined
    if (this.context.selection) {
      this.context.selection.select(this.props.tabFor);
    }

    if (this.props.onClick) {
      this.props.onClick(event);
    }
  }

  render() {
    return (
      <Context.Consumer>
        //context from `Provider`
        {(selection) => {
          return (<button
            default={selection.defaultSelection}
            onChange={selection.onChange}
          >
            {children}
          </button>);
        }}
      </Context.Consumer>
    );
  }
}

But how to get access to conext in component methods or in the constructor like in old API from this.context?

fasenberg
  • 1,295
  • 2
  • 8
  • 13
  • Put `Context.Consumer` one level higher in the component tree and pass what you need to your `Consumer` as a prop – SrThompson May 23 '18 at 14:30

0 Answers0