0

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);
       }
    });
}
  • this is literally what [`refs`](https://facebook.github.io/react/docs/more-about-refs.html) are for =) That said, why do you need to access its as DOM node instead of just writing your code render-backend-agnostically? – Mike 'Pomax' Kamermans Feb 23 '16 at 01:23

2 Answers2

1

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>
  );
}
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
0

Wouldn't the DOM node just be this.refs.theDiv?