2

I am using React with Typescript and would like to know how to figure out the coordinates of a sub-component in a React class I wrote.

I already found this article: https://medium.com/@chung.andrew7/finding-the-absolute-positions-of-react-components-fda1c5bc9ab

And this: Get div's offsetTop positions in React

Here it is stated that this is usually done with getBoundingClientRect(), but I can't find any way how to do this with TypeScript, or what property or a ref this would be located on.

If I assign my component as _searchBarPreview: React.RefObject<{}>; by passing the following as "ref" prop on the element:ref={this._searchBarPreview}, I can't access the said function on that object at all.

What works is to assign the child component I want to get clients of an id and obtain the coordinates via:

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

but there HAS to be a better way.

Any quick guidance?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Sossenbinder
  • 4,852
  • 5
  • 35
  • 78

1 Answers1

0

Seem like that is the only way or you can use react-dom

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
    const data = ReactDOM
      .findDOMNode(this.myRef)
      .getBoundingClientRect();
  }

  render() {
    return <div ref={this.myRef} />
  }
}
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60