0

I'm trying to use some nested render props to compose a button that optionally takes an icon, which in turn optionally takes a tooltip that will show when the icon is hovered or clicked. To do this I think I will need to pass a reference to the Icon down to the child Tooltip component.

Based on what I have read here I'm doing

  // Icon

  componentDidMount() {
    this.iconInstance = ReactDOM.findDOMNode(this);
    console.log('Icon mounted, instance', this.iconInstance);
  }

  render() {
    console.log('Icon render iconInstance', this.iconInstance);
    return (
      <span style={{ display: 'inline' }}>
        <span>{this.props.iconText}</span>
        {this.props.tooltip({ iconInstance: this.iconInstance })}
      </span>
    );
  }

And then within Tooltip, a listener would be added

  componentDidMount() {
    console.log('Tooltip mounted', this.props);
    // fails because iconInstance is undefined
    // this.props.iconInstance.addEventListener(
    //   this.props.mouseEvent,
    //   this.showTooltip
    // );
  }

Immediately after I set this.iconInstance, it can be logged so that seems to be working. However in the render function I'm getting undefined.

There might be a way to use forwardRef to do this, however I could not find a way to pass the Tooltip component as a render prop from the App component down through Icon and add a ref prop to it eg, {this.props.tooltip(this.iconInstance)} gets an error saying you can't pass refs like that and it will fail.

Full code

1252748
  • 14,597
  • 32
  • 109
  • 229
  • Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Sep 07 '18 at 06:35

1 Answers1

-2

ComponentDidMount is a method which gets executed after the render method is called for the first time. It is ComponentWillMount method which is called before the render method is executed.

QuickCoder
  • 415
  • 1
  • 4
  • 7
  • It is in context with what you were discussing with the above person. – QuickCoder Sep 06 '18 at 19:18
  • Ah, then this should be a comment in the above discussion, not its own answer, but anyway, this is not really in question. Thanks though. – 1252748 Sep 06 '18 at 19:22
  • We need 50 as the minimum reputation score to comment on any post and by reading my answer you downvoted and decreased my score by 1. – QuickCoder Sep 06 '18 at 19:30