title: Change value in react js on window resize
body: <p>I'm building a photo gallery in react js. Obviously it's going to have to be responsive and I've tackled this by setting values like so in the component's render method:</p>
  
  <pre><code>let thumbWidth = window.innerWidth &gt;= 480 ? 75 : 100;
  </code></pre>
  
  <p>The problem is that I need the const value to change when the window is resized. My my first attempts was to build a function like so and bind it in the constructor:</p>
  
  <pre><code>getThumbWidth = (vpWidth) =&gt; {
      if(vpWidth &gt;= 480 ) {
          this.setState({thumbSize: 120}); 
       } else {
          this.setState({thumbSize: 50}); 
       }
  }
  </code></pre>
  
  <p>This worked in terms of setting the variable's initial value but how do I trigger the function when the window resizes?</p>
  
  <p>Have tried adding a resize function:</p>
  
  <pre><code>resize = () =&gt; this.getThumbWidth()
  </code></pre>
  
  <p>...and then changing getThumbWidth so that it sets the value in the component's sate - the idea being that when state is updated the component automatically rerenders:</p>
  
  <pre><code>getThumbWidth = (vpWidth) =&gt; {
      if(vpWidth &gt;= 480 ) {
          this.setState({thumbSize: 120}); 
       } else {
          this.setState({thumbSize: 50}); 
       }
  }
  </code></pre>
  
  <p>And then calling it via lifecycle methods as suggested in several other solutions but the event listener does not appear to be firing:</p>
  
  <pre><code>componentDidMount() {
      window.addEventListener('resize', this.resize)
  }
  
  componentWillUnmount() {
      window.removeEventListener('resize', this.resize)
  }  
  </code></pre>
  
  <p>Still not working though... any ideas?</p>