mre12345
mre12345

Reputation: 1127

setState not working in componentDidMount() - React

I have been having a few problems with using the setState function in componentDidMount().

What I am trying to do: I am trying to make an HTML5 circle responsive (Go bigger if browser window is bigger and vice versa).

What I have done so far: I have been storing the dimensions in state called containerDim. By Default this is set to null. Here is a very basic implementation of what I've done:

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 am trying to do with this code is to get the width and height of "responseContainer" and pass it as a prop to the <Circle /> component.

The above does not work as the setState does not change the state whatsoever.

Any help would be greatly appreciated!

EDIT:

This "Works" but I feel that it is not correct and there should be a better way:

 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}
});

Upvotes: 6

Views: 7159

Answers (2)

pinturic
pinturic

Reputation: 2263

The component does not listen to state modifications in didMount; that means that even if the state is updated the repaint is not triggered.

Upvotes: 1

David Guan
David Guan

Reputation: 4290

Could you try this?

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);
  }

Upvotes: 0

Related Questions