Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get component's position by ref in React?

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?

like image 545
JustLogin Avatar asked Dec 15 '16 13:12

JustLogin


People also ask

How do you get the offsetTop in React?

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.

How do I get DOM element from ref?

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.


1 Answers

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()
like image 161
Davin Tryon Avatar answered Oct 25 '22 09:10

Davin Tryon