Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
Kevin Wang Avatar asked Jul 02 '26 08:07

Kevin Wang


1 Answers

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.

like image 122
Alexandre Kirszenberg Avatar answered Jul 03 '26 20:07

Alexandre Kirszenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!