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 forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React.
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.
Firstly, let's pass data between a parent component and a child component. . First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With