Home > Software engineering >  How to find the positions and width/heights of react components?
How to find the positions and width/heights of react components?

Time:10-17

I am trying to build a react app, and what I am trying to do is have the app, and have a section/component within it, which I will need the positioning and width and height of. But when I try to use document.getElementById('area').getBoundingClientRect().width (to find the width for example), I am not able target the component. Instead, my code seems to fail unless I use document.getElementById('root').getBoundingClientRect().width.

My file:

import './App.css';

class App extends React.Component {
  render() {
    return (
      <main>
        <Space />
      </main>
    );
  }
}

class Space extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div class="space">
        <h1>{document.getElementById('root').getBoundingClientRect().width}</h1>
      </div>
    );
  }
}

export default App;

I have to use 'root' instead of 'area' for it to work. A "Space" is just an area that I need to know the coordinates of. Thanks.

CodePudding user response:

In most cases, you should use a react ref to get the element, not document.getElementById. For example, this code renders a div, and then in componentDidMount can access the underlying DOM element:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.mainDiv = React.createRef();
  }

  componentDidMount() {
    console.log(this.mainDiv.current.getBoundingClientRect().width);
    // Possibly set state to rerender now that you know the width
  }

  render() {
    return (
      <div ref={this.mainDiv}>
        Hello World
      </div>
    );
  } 
}

getElementId can sometimes be useful if you need to get an element that's outside of the react component tree, but that's uncommon. If you're trying to use getElementId and it's not working, make sure an element with that id exists. Your question didn't show any elements with the ids "root" or "area", so check to make sure those are part of the page.

CodePudding user response:

To access the DOM properties in react there is a concept in react called refs.Refs allow us to directly access the dom elements. So refer this codesandbox to know how to make it work in FUNCTIONAL COMPONENT with useRef hook.

Refer This, will explain with code and also see the console in the sandbox:

LINK

Also this might explain more theoritically : LINK

  • Related