How to get the width and height of a DOM element in React?

In React, you can use ref to access the width and height of DOM elements.

First, create a ref object within the component and then pass it to the DOM element from which you want to get the width and height.

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

  componentDidMount() {
    const element = this.myRef.current;
    const width = element.offsetWidth;
    const height = element.offsetHeight;
    console.log('Width:', width);
    console.log('Height:', height);
  }

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

In the componentDidMount lifecycle method, you can use ref.current to obtain a reference to the DOM element. Then, you can use the offsetWidth and offsetHeight properties to obtain the width and height.

Please note that to ensure you can access the width and height of DOM elements after component rendering, place the code to retrieve width and height in the componentDidMount lifecycle method.

In addition, you can also use other lifecycle methods, such as componentDidUpdate, to obtain the width and height of DOM elements.

bannerAds