I'm dealing with a React component that uses React.findDOMNode(this) to obtain data about its position in the DOM, then it renders its children through props (the purpose is to compute a certain value to pass to its onChange method).
componentDidMount() {
this.node = ReactDOM.findDOMNode(this);
}
componentDidUpdate() {
this.node = ReactDOM.findDOMNode(this);
this.doThingsWithTheNode()
}
render() {
return this.props.children
}
Since I'm migrating this to a functional component and findDOMNode is deprecated in general I'm looking into a way to do use refs instead. My problem is that I don't know what props.children is going to hold, so (as far as I understand) I can't forward a ref to its contents.
I tried a solution along these lines (I'd be fine restricting to a single child), but this.ref isn't set to any value:
render() {
const child = React.Children.only(this.props.children)
return (
React.cloneElement(child, { ref: el => this.ref = el })
)
}
I could wrap the children in a div and set my ref on that, as far as I understand that would work fine for the most part.
Is there another "react" solution to this problem or is this kind of scenario something that the React team has judged to be an anti-pattern to be avoided?
---EDIT---
Re-reading the documentation for forwardRefs I realized that the docs themselves propose to use a div wrapper to set the ref on a valid html element, or as is the case with the example use an intermediate component to hold that div.
---I am the parent---
const ref = createRef()
return <Child ref={ref}/>
---I am the child---
const Child = React.forwardRef((props, ref) => (
<div ref={ref}>
{props.children}
</div>)
);