Finding the absolute positions of react components

Andrew Chung
2 min readMar 4, 2017

--

Note: this post was written a while back, so a quick update. findDomNode is soon to be deprecated, so it’s probably not best to depend on it. Best would probably be to use the new refs api which takes a callback as a function ex.


render() {
return <Comp refs={ el =>
this.setState( state => ({
pos: {
...state.pos,
[el.name]: el.getBoundingClientRect()
}))
} />;
}

Accessing the position of elements in the browser has always been tricky. In react, the problem is compounded by the fact that DOM elements can not be directly accessed since they are blocked by a react component shell.

CSS

Accessing the position of an element can be done to some degree with CSS through jQuery’s ‘.position’ or ‘.offset’ methods.

/* CSS file */
.element {
position: absolute;
top:0;
left:0;
}//Javascript file$('.element').offset();

The problem with this approach, however, is that it requires a jQuery framework on top of a React library, which would be over kill for just a coordinate point.

.getBoundingClientRect()

The ‘.getBoundingClientRect’ method returns an object of the positions of the element’s left, right, top, and bottom border. These properties are independent of any css presets. It is called directly on the html element in the document.

document.getElementById('app').getBoundingClientRect();

The .getBoundingClientRect() can be called on any element, but it is not able to be called directly on react components. As a result, we have to use the findDOMNode function given by react dom to locate the corresponding element of the react component in question.

ReactDOM
.findDOMNode(this.refs['UniqueElementIdentifier'])
.getBoundingClientRect(); //outputs <h3> coordinates
render () {
return (<h3 ref='UniqueElementIdentifier'>
Located with BoundingClient
</h3>);
}

Attaching a ‘ref’ attribute will enable the findDOMNode function to locate <h3> element in the DOM. After which, we can find it’s exact location using getBoundingClientRect();

The beauty of this approach is that it can be used to locate React components too, not just html elements.

ReactDOM
.findDOMNode(this.refs['UniqueElementIdentifier'])
.getBoundingClientRect(); //outputs <h3> coordinates
render () {
return (<H3ReactComponent ref='UniqueElementIdentifier' />);
}
var H3ReactComponent = (props) => {
return (<h3>
Located with BoundingClient
</h3>)
}

ReactDOM will locate the parent element, in this case <h3>, of the react component. This way one can reliable locate the position of any react component on the browser.

--

--