Action on window resize in React

Viewed 14117

I am trying to make a resize action which will return the width of the window and dynamically render it using react.

This is what i got:

class Welcome extends React.Component {
    constructor() {
        super();
        this.state = {
          WindowSize : window.innerWidth
        }
        this.handleResize = this.handleResize.bind(this);
    }
    handleResize(WindowSize, event) {
        this.setState({WindowSize: window.innerWidth})
    }
    render() {
    return <h1  onresize={this.handleResize(this.state.WindowSize)} hidden={(this.state.WindowSize  < 1024) ? "hidden" : ''}>Hello</h1>;
  }
}
ReactDOM.render(
   <Welcome/>,
   document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
  <div id="root">
</div>
This works whenever i reload a page but not when i am changing window size by itself.

2 Answers

It is also possible using React Hooks

import React from 'react';


function useWindowDimensions() {
  const [width, setWidth] = React.useState(window.innerWidth);
  const [height, setHeight] = React.useState(window.innerHeight);

  const updateWidthAndHeight = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };

  React.useEffect(() => {
    window.addEventListener("resize", updateWidthAndHeight);
    return () => window.removeEventListener("resize", updateWidthAndHeight);
  });

  return {
    width,
    height,
  }
}
const App = () => {
  const { width, height } = useWindowDimensions()

  return (
    <div>
      <div className="App">
        <h2>width: {width}</h2>
        <h2>height: {height}</h2>
        <p>Resize the window.</p>
      </div>
    </div>
  );
};

export default App;
Related