SomeUnusedUsername
SomeUnusedUsername

Reputation: 172

React: How to access refs in this.props.children

I want to call a function of a child component.
Is there a possibility to get refs from this.props.children in React.

var ComponentSection = React.createClass({

    componentDidMount: function() {
      // How to access refs in this.props.children ?
      this.refs.inner.refs.specificPanel.resize();
    },

    render: function () {
        return (
          <div className="component-section" ref="inner">
            {this.props.children}
          </div>
        );
    }
});

var Panel = React.createClass({

    resize: function() {
        console.log('Panel resizing');
    },

    render: function () {
        return (
          <div className="Panel">
            Lorem   ipsum dolor sit amet 
          </div>
        );
    }
});

var MainComponent = React.createClass({
    render: function () {
        return (
           <ComponentSection>
            <Panel ref="specificPanel"></Panel>
           </ComponentSection>
        );
    }
});

ReactDOM.render(
  <MainComponent></MainComponent>,
  document.getElementById('container')
);

I made a little demo: https://jsfiddle.net/69z2wepo/26929/

Thanks in advance

Upvotes: 8

Views: 11368

Answers (2)

hon2a
hon2a

Reputation: 7214

Ref in React is a relationship between a component and its owner while what you want is a relationship between an element and its parent. A parent-child relationship is opaque, the parent only receives the child elements on render and never gets access to the resolved components.

In your case, the ref="specificPanel" establishes a link from the MainComponent to the Panel. If you want to call methods of Panel from ComponentSection, it should own the Panels instead of receiving them as children.

You could always get creative with React.Children.map and React.createElement (cloning the elements by hand and thus stealing them from the original owner), but this introduces some serious potential pitfalls. A better approach would likely be re-thinking the ownership structure of your component tree.

Upvotes: 7

Daniel B
Daniel B

Reputation: 8879

You are trying to set a ref on a <div> instead of a React component.

You could also refactor your code so that only <ComponentSection> needs to know about the <Panel> component, and render it in it's render function.

var ComponentSection = React.createClass({
  componentDidMount: function() {
    this.refs.inner.resize();
  },

  render: function() {
    return ( 
        <div className="component-section">
            <Panel ref="inner"/>
        </div>
    );
  }
});

var MainComponent = React.createClass({
  render: function() {
    return ( 
        <ComponentSection /> 
    );
  }
});

Here is a working JSFiddlle.

Upvotes: 4

Related Questions