I'm using React 15.3.1 for my app. So, I need to get Component
x and y positions in it's parent. The child is rendered like this:
<Icon key={key} ref={(c) => this['icon' + key] = c}}/>;
And this is how I try to access Icon
(which is basically a div
) position:
let icon = this['icon' + this.state.currentIcon.id];
icon.getBoundingClientRect(); //Error: "getBoundingClientRect" is not a function
The child is correct, I can see it's props
in the debugger. But I cannot see any properties like getBoundingClientRect
, left
, top
or any other position attributes. What I need to do to get them?
To get a div's offsetTop positions in React, we can get it from the ref assigned to the element. to assign the inputRef to the input. Then we get the offsetTop property from the inputRef. current property which has the input element.
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.
Your ref
will refer to Icon
, which I'm guessing is a React Component. You need to resolve the actual React Element (DOM element) before the getBoundingClientRect
method will be available.
You can do this through the ReactDOM.findDOMNode() function.
let icon = this['icon' + this.state.currentIcon.id];
const domNode = ReactDOM.findDOMNode(icon);
domNode.getBoundingClientRect()
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