Handling Browser Window Resize in ReactJS

| Comments

If you want to handle some use cases like “I want to update a div container width on browser window resize in react application” then you are in the right place.

In jQuery it’s fairly simple like below.

1
2
3
4
5
6
$( window ).resize(function() {
  var reelContainerWidth = $(window).width() - 400;

  // sets the width of reel-container to (window size - 400px)
  $("#reel-container").width(reelContainerWidth);
});

In the React world we have do it in slightly different way.

  1. Set initial width in default state
  2. Calculate viewport width each time the browser windows change size
  3. Re-render our component by passing the updated width through state

React way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var React = require("react"),
ReactDOM = require("react-dom");

var ReelContainer = React.createClass({

  getInitialState: function() {
    return {
      reelContainerWidth: 100
    };
  },

  /**
   * Calculate & Update state of new dimensions
   */
  updateDimensions() {
    const reelContainerWidth = window.innerWidth - 400;

    // sets the width of reel-container state to (window size - 400px)
    this.setState({ reelContainerWidth: reelContainerWidth });
  }

  /**
   * Add event listener
   */
  componentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions);
  }

  /**
   * Remove event listener
   */
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
  }

  render(): React.Element {
    const reelContainerWidth = { width: this.state.reelContainerWidth };

    return(
      <div id="reel-container" style={reelContainerWidth}>
         Reel Content
      </div>
    );
  }
}

module.exports = ReelContainer;

Comments