Bill
Bill

Reputation: 25555

ReactJS: Access context from base component

I'm trying to create a base component that can handle UI themes. The theme is passed to components via context, but the base component that I've created is not receiving the context.

class DetailView extends ThemedComponent {
  constructor(props) {
    super(props);
  }

  render() {
    return <div>Detail View</div>;
  }
}

export default DetailView;

class ThemedComponent extends Component {
  constructor(props, context) {
    super(props);
    // context here is undefined
  }
}

ThemedComponent.contextTypes = {
  theme: PropTypes.object,
};

export default ThemedComponent;

I can get the context from DetailView if it extends Component directly and all that works fine. However, when I try to get the context within ThemedComponent it is always undefined.

What's the right way to create a common base component that can perform operations using the components context?

Upvotes: 0

Views: 174

Answers (1)

hex13
hex13

Reputation: 520

You have to pass context to super in DetailView:

class DetailView extends ThemedComponent {
     constructor(props, context) {
          super(props, context);
     }
     .........
}

Upvotes: 1

Related Questions