2

I'm in need of getting the width of the browser when i resize the browser in real time. So far i've found a solution which gives the width but it's not in real time. The value is updated only after i refresh the web page. How can i get the value as i resize the browser.

My approach

render() {

var windowWidth = window.innerWidth;

return (

      <div className="body_clr">

        {windowWidth}

      </div>

)
}

This solution works if i refresh the page. But i want to get the width as i resize because i have to execute a function at a specific screen size.

CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • 1
    https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react – brk Aug 08 '18 at 10:27

2 Answers2

9

Here's a way to do this:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      height: 0,
      width: 0
    };

    window.addEventListener("resize", this.update);
  }

  componentDidMount() {
    this.update();
  }

  update = () => {
    this.setState({
      height: window.innerHeight,
      width: window.innerWidth
    });
  };

  render() {
    return (
      <React.Fragment>
        <p>height: {this.state.height}</p>
        <p>width: {this.state.width}</p>
      </React.Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working CodeSandbox here.

Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
6

You can use event listeners:

window.addEventListener("resize", function() {
  return window.innerWidth;
});
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36