Kevin Wang
Kevin Wang

Reputation: 3330

ReactJS - Assign context/owner in 13.x

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:

  1. Find a way to assign context within a component upon render or manually switch the owner of an element.
  2. Reconstruct elements by passing in props and tagnames
  3. Wait for 0.14

2 is really un-maintainable for more complicated structures and 3 is the surrender, is there any ways I can achieve 1?

Upvotes: 3

Views: 220

Answers (1)

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36408

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.

Upvotes: 1

Related Questions