Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass this.refs as property in jsx in React.js

I'm trying to pass 1 node as a property of another React component like this:

  render: function() {
    return (
      <div>
        <div ref='statusCircle'></div>
        <Popover trigger={ this.refs.statusCircle }></Popover>
      </div>);
    );
  }

But in the Popover, this.props.trigger is NULL.

Is there anything wrong with my code?

How can I pass a node-ref to another React component as property?

like image 373
haotang Avatar asked Jan 07 '23 19:01

haotang


1 Answers

You've misunderstood the component lifecycle in React. See here: Link

See this fiddle. https://jsfiddle.net/uzvoruf7/
Open your console, inspect the code for the "Composite" component, and see the lifecycle hooks.

var Popover = React.createClass({
  render: function() {
    return (<div>This is a pop-over</div>);
  }
});

var Composite = React.createClass({
  componentDidMount: function() {
    console.log(this.refs.statusCircle); //ok, exists.
  },
  render: function() {
    console.log(this.refs.statusCircle); //doesn't exist, sorry.
    return (
      <div>
        <div ref='statusCircle'></div>
        <Popover trigger={this.refs.statusCircle}></Popover>
      </div>
    );
  }
});

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

"refs" come alive once the DOM has been rendered.

Therefore, it follows that inside that return statement, the dom has not been rendered yet, hence the reference is null (or all references are null so to speak).

However, inside componentDidMount, you can see that your references are available just as one would expect.

This is a common error: a possible code smell that needs refactoring. Usually (not always), passing down dom-references is indicative of an imperative thought process and is not the React way. I would suggest an improvement but I'm not aware of your use-case.

like image 94
BluePill Avatar answered Jan 16 '23 00:01

BluePill