AnnaSm
AnnaSm

Reputation: 2300

Why is Context not being passed to my HOC

I have a component that is using a HOC. The HOC needs this.context but for some reason this.context is not being passed. What am I doing wrong? ty

component:

import React, { Component } from 'react';
import withTracking from './hocs/withTracking';

class NamePage extends Component {
  componentDidMount() {
    console.log(this.context.mixpanel) // WORKS
  }
  render() {
    return (
      ...
    );
  }
}

NamePage.contextTypes = {
  mixpanel: PropTypes.object.isRequired
};

export default withTracking('View Page: NamePage')(NamePage);

hoc

import { lifecycle } from 'recompose';

export function withTracking(eventTitle) {
    return lifecycle({
        componentDidMount() {
          console.log(this.context.mixpanel) // UNDEFINED - fail-y?
        }
    });
}

export default withTracking;

The console.log is returning undefined where it returns correct if I output in the component.

What am I doing wrong? Thanks

Upvotes: 1

Views: 156

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

ContextTypes are specified only for the NamePage component, in order for you to use it with the HOC you need to specify it on the wrappedComponent instance

const WrappedNamePage = withTracking('View Page: NamePage')(NamePage);

WrappedNamePage.contextTypes = {
  mixpanel: PropTypes.object.isRequired
};

export default WrappedNamePage

Upvotes: 1

Related Questions