faceyspacey.com faceyspacey.com - 2 months ago 6
React JSX Question

is there any way to access the parent component instance in React?

I know it's not a functional approach to be able to do something like

this.parent
in a React component, and I can't seem to find any properties on a React component instance that lead to the parent, but I'm just looking to be able to do some custom things where I need this.

Before anyone wastes their time explaining it's not the functional React "way," understand that I need this because of the following I'm trying to achieve:

Build a transpiler for Meteor's Spacebars templating engine, whose rendering model does take into consideration parent components/templates.

I've already built a transpiler that modifies the output jsx to achieve this. I do this by passing in
parent={this}
in all child components composed. However, after the fact it occurred to me that maybe I simply don't know of something that will give me a way to access the parent component instance without additional transpilation modifications.

Any tips would be much appreciated.

Answer

You've already recognized that this is not a good thing to do almost always, but I'm repeating it here for people that don't read the question very well: this is generally an improper way to get things done in React.

There's nothing in the public API that will allow you to get what you want. You may be able to get to this using the React internals, but because it's a private API it's liable to break at any time.

You can get the internal instance of the current component using this. _reactInternalInstance. In there, you can get access to the element via the _currentElement property, and then the owner instance via _owner._instance.

Here's an example:

var Parent = React.createClass({
  render() {
      return <Child v="test" />;
  },

  doAThing() {
    console.log("I'm the parent, doing a thing.", this.props.testing);
  }
});

var Child = React.createClass({
  render() {
    return <button onClick={this.onClick}>{this.props.v}</button>
  },

  onClick() {
    var parent = this._reactInternalInstance._currentElement._owner._instance;
    console.log("parent:", parent);
    parent.doAThing();
  }
});

ReactDOM.render(<Parent testing={true} />, container);

And here's a working JSFiddle example: http://jsfiddle.net/BinaryMuse/j8uaq85e/

Comments