简体   繁体   中英

Pass React Ref from parent to child in order to get DOM element

I have a parent and a child component. I need to access the parent's HTMLelement in the child component.

I have a working but unclean solution involving this.setState({ domNode: ReactDOM.findDOMNode(this) }); in the parent's componentDidMount which is just wrong on many levels.

How can i do this using createRef() in the parent to pass its ref as a prop to the child and then how do i get the DOM node with type HTMLElement from the ref?

The best solution that doesn't involve any hack would be to pass a function from parent to child that return the ref of the element to be access

Parent:

constructor(props) {
    super(props);
    this.domElem = React.createRef();
}

getElem = () => {
    return this.domElem;
}

render() {
    return (
       <div>
           <div id="elem" ref={this.domElem}>Test Elem</div>
           <Child getParentElem={this.getElem}/>
       </div>
    )
}

Child:

getParentRef = () => {
   const elem = this.props.getParentElem();
}

The solution of @Shubham Khatri is proper to be mentioned. The small correction I want to show, there is no need to invoke a callback function getElem() from child to parent to receive the parent's ref. It can be passed directly the ref to child <Child getParentElem={this.domElem}/> I see few user complaining to receive {current: null} at child. Please check if the components UI is delivered by a framework, like eg Semantic-UI. Probably there could be other methods to hook a ref from a component. In Semantic-UI have to be wrapped the parent component in <Ref innerRef={ ... }> ... </Ref>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM