React: `context` always empty object

Created on 28 Sep 2016  路  2Comments  路  Source: facebook/react

I'm trying to set a context in my React App, but somehow i can't acces context from childrens. This is the parent class:

import React from 'react'
import MenuBar from './MenuBar.js'

export default class App extends React.Component {

  static childContextTypes = {
    prop:    React.PropTypes.bool
  };

  getChildContext(){
    return {
      prop: true
    }
  }

  render() {
    return (
      <div>
        <MenuBar />
      </div>  
    )
  }

}

And here is my children class:

import React, { Component } from 'react';

export default class MenuBar extends Component {

  constructor(props, context){
    super(props,context)
    console.log(this.context)
    console.log(context)
  }

  render() {
    console.log(this.context)
    return (
      <div>MenuBar</div>
    );
  }
}

All the console.log's return an empty object, am i doing something wrong?

Most helpful comment

You have to specify contextTypes on MenuBar for any context properties to be passed to it.

class MenuBar extends React.Component {

  // you're missing this
  static contextTypes = {
    foo: React.PropTypes.bool,
  };

  constructor(props, context){
    super(props,context)
    console.log(this.context)
    console.log(context)
  }

  render() {
    console.log(this.context)
    return (
      <div>MenuBar</div>
    );
  }
}

See this working example.

All 2 comments

You have to specify contextTypes on MenuBar for any context properties to be passed to it.

class MenuBar extends React.Component {

  // you're missing this
  static contextTypes = {
    foo: React.PropTypes.bool,
  };

  constructor(props, context){
    super(props,context)
    console.log(this.context)
    console.log(context)
  }

  render() {
    console.log(this.context)
    return (
      <div>MenuBar</div>
    );
  }
}

See this working example.

omg... thank you!!

Was this page helpful?
0 / 5 - 0 ratings