JustLogin
JustLogin

Reputation: 1890

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?

Upvotes: 12

Views: 26117

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

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()

Upvotes: 17

Related Questions