SetState does not work in component DidMount () - Reacts

I am having several problems using the setState function in the DidMount () component.

What I'm trying to do: I'm trying to make the HTML5 circle responsive (go more if the browser window is larger and vice versa).

What I have done so far: I kept the dimensions in a state called containerDim. By default, this value is null. Here is a very simple implementation of what I did:

class App extends React.Component  {
  constructor(props)  {
    super(props);
    this.state = {containerDim: null};
    this.resizeCircle = this.resizeCircle.bind(this)  //To not loose value of this
  }

  componentDidMount()  {

    var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

    this.setState({
      containerDim: {width:dimensions.width, height: dimensions.height}
    });

   window.addEventListener("resize", this.resizeCircle));

  }

 resizeCircle()  {  //THE RESIZING WORKS, THE initial setting of state doesn't
   var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

    this.setState({
      containerDim: {width:dimensions.width, height: dimensions.height}
    });

 }



  render()  {
    return (
     <div ref={"responsiveContainer"} >
       <Circle dimensions={this.state.containerDim} />
     </div>
    );
  }
} 

//Circle component

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

  componentWillReceiveProps()  {

    console.log(this.props.dimensions); //THIS LOGS OUT NULL

  }

  render()  {
    CIRCLE GOES HERE
  }

}

Basically, what I'm trying to do with this code is to get the width and height of the "responseContainer" and pass it as a support for the component <Circle />.

The above does not work as setState does not change state at all.

Any help would be greatly appreciated!

EDIT:

"", , , :

 var dimensions = window.getComputedStyle(this.refs.container);

  setTimeout(function()  {


  this.setState({
    screenDim:{width:dimensions.width, height:dimensions.height}
  });
}.bind(this),0);

this.setState({
  screenDim:{width:dimensions.width, height:dimensions.height}
});
+4
2

didMount; , , .

+1

?

componentDidMount()  {
    setInterval((function() {
      var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

      this.setState({
        containerDim: {width:dimensions.width, height: dimensions.height}
      });
    }).bind(this), 1000);
  }
0

Source: https://habr.com/ru/post/1627253/


All Articles