Search code examples
reactjsreact-dom

How to get the DOM node of a child


I want to access the DOM node of a child component defined in a parent component. In the sample below I've tried both the "try1" and "try2" methods and neither works. How do I get the DOM node for the "theDiv" ref?

<Form>
    <Frame>
        <div ref="thediv" />
    </Frame>
</Form>

Form.render() {
    return (
       <Frame>
           <div ref="theDiv" />
       </Frame>
}

try1.Frame.componentDidMount() {
    let theDiv = ReactDOM.findDOMNode(this.refs.theDiv);
}

try2.Frame.componentDidMount() {
    React.Children.forEach(this.props.children, child => {
       if (child.ref === "theDiv") {
           let theDiv = ReactDOM.findDOMNode(child);
       }
    });
}

Solution

  • It might be more helpful to explain why you want to do this?

    For now, you can use a ref prop to get a reference to the element, then pass it back the parent with a callback.

    // Parent Component
    onChildLoad(element) {
      // do stuff here
    },
    render() {
      return (
        <Child onChildLoad={loadedChild}>
          // ...
        </Child>
      );
    }
    
    // Child Component
    render() {
      return (
        <div ref={this.props.onChildLoad}></div>
      );
    }