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.