I am trying to render a child element that has already been initialized and is passed through a prop. My child depends on its context, yet I don't know how to apply that context before a render. Example:
http://jsfiddle.net/5qyqceaj/1/ (code below on React 0.13.3):
var Parent = React.createClass({
childContextTypes: {
test: React.PropTypes.string
},
getChildContext: function() {
return { test: "Working :)" };
},
render: function() {
return (
<div>
<b>Initialized Globally:</b><br/> {this.props.child}
<hr/>
<b>Initialized Inline:</b><br/> <Child/>
</div>
);
}
});
var Child = React.createClass({
contextTypes: {
test: React.PropTypes.string
},
render: function() {
return <div><h1>Context: {this.context.test || "Broken"}</h1></div>;
}
});
var ChildInstance = <Child/>;
React.render(<Parent child={ChildInstance} />, document.getElementById('container'));
In the example above, <Child/> when initialized globally fails to inherit the context passed by Parent.
According to https://github.com/facebook/react/issues/3451#issuecomment-104978224, this is an open issue with React 0.13.x where context is currently assigned via the owner and by 0.14 they will have it inherited from parents.
There are 3 ways I can imagine solving this:
2 is really un-maintainable for more complicated structures and 3 is the surrender, is there any ways I can achieve 1?
You can use React.cloneElement to re-assign the owner of a React element. It will return a new element. Note that you will need to pass a new ref property, otherwise the previous owner will be preserved.
In your case, you would clone this.props.child in the render method of Parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With