How to get a react component's size (height/width) before render?

前端 未结 6 1224
天命终不由人
天命终不由人 2020-12-03 00:22

I have a react component that needs to know its dimensions ahead of time, before it renders itself.

When I\'d make a widget in jquery I could just <

6条回答
  •  情话喂你
    2020-12-03 01:13

    As it was already mentioned, you can't get any element's dimensions until it is rendered to DOM. What you can do in React is to render only a container element, then get it's size in componentDidMount, and then render rest of the content.

    I made a working example.

    Please note that using setState in componentDidMount is an anti-pattern but in this case is fine, as it is exactly what are we trying to achieve.

    Cheers!

    Code:

    import React, { Component } from 'react';
    
    export default class Example extends Component {
      state = {
        dimensions: null,
      };
    
      componentDidMount() {
        this.setState({
          dimensions: {
            width: this.container.offsetWidth,
            height: this.container.offsetHeight,
          },
        });
      }
    
      renderContent() {
        const { dimensions } = this.state;
    
        return (
          
    width: {dimensions.width}
    height: {dimensions.height}
    ); } render() { const { dimensions } = this.state; return (
    (this.container = el)}> {dimensions && this.renderContent()}
    ); } }

提交回复
热议问题