Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React `context` always empty object

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, what am i doing wrong?

like image 628
Gerard Rodes Vidal Avatar asked Sep 28 '16 18:09

Gerard Rodes Vidal


1 Answers

Context is mainly used by library authors, for example, React Router and Redux - two widely used React libraries - currently rely on context. Here is a nice summary written by Dan Abramov (author of Redux): https://stackoverflow.com/a/36431583/4186037

The missing part in your code is the following static variable which needs to be present on your child component:

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

Here is a demo: http://codepen.io/PiotrBerebecki/pen/LRLgJP and below is the full code.

class App extends React.Component {
  static childContextTypes = {
    prop: React.PropTypes.bool
  };

  getChildContext() {
    return {prop: true};
  }
  render() {
    return <MenuBar/ >;
  }
}


class MenuBar extends React.Component {
  constructor(props, context) {
    super(props, context);
    console.log('in constructor', context.prop) // logs: true
  }

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

  render() {
    console.log('in render', this.context.prop) // logs: true
    return (
      <div>MenuBar</div>
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById('app')
);

For React v15.5, and above, use PropTypes instead of React.PropTypes, and import PropTypes like so:

import PropTypes from 'prop-types';

See: https://reactjs.org/docs/typechecking-with-proptypes.html for more information.

like image 69
Piotr Berebecki Avatar answered Nov 08 '22 20:11

Piotr Berebecki