Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React context is undefined when the children are rendered using this.props.children

I am facing a really annoying behaviour in React. I would like to pass the context from the parent component to the child component using getChildContext. Everything works fine as long as I don't use {this.props.children} in the render function. If I do so, the context of the children component is undefined.

I am attaching a code example that reproduce this behaviour. I can't figure out why the bar filed of context of the component Baz is undefined.

var Baz = React.createClass({
 contextTypes: {
   bar: React.PropTypes.any
 },
 render: function() {
   console.log(this.context);
   return <div />;
 }
});

var Bar = React.createClass({
 childContextTypes: {
   bar: React.PropTypes.any
 },

 getChildContext: function() {
   return {
     bar: "BAR"
   };
 },

 render: function() {
   return (<div>{this.props.children}</div>);
 }
});

var Foo = React.createClass({
 render: function() {
   return <Bar>
      <Baz />
   </Bar>;
 }
});

console.log(React.version);

React.render(<Foo />, document.body);

Console Output:

Warning: owner-based and parent-based contexts differ (values: `undefined` vs `BAR`) for key (bar) while mounting Baz (see: http://fb.me/react-context-by-parent)
Inline JSX script:10 Object {bar: undefined}

JSFiddle: https://jsfiddle.net/3h7pxnkx/1/

like image 260
Giuseppe Pes Avatar asked May 19 '15 17:05

Giuseppe Pes


1 Answers

So it appears that all of the components get the child context of where they are created. In this case <Baz /> is created as a part of Foo, so it gets the child context from Foo, which is why it's undefined.

Couple of options.

1) Set the child context on Foo.
2) Recreate the <Baz> child in Bar. You can do this with cloneWithProps.

render: function() {
   console.log(this);
   return React.addons.cloneWithProps(this.props.children)
}

Updated fiddle: https://jsfiddle.net/crob611/3h7pxnkx/2/

Issue on react project discussing it: https://github.com/facebook/react/issues/3392

like image 136
Crob Avatar answered Oct 23 '22 22:10

Crob