Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action on window resize in React

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.
like image 796
Mac Avatar asked Aug 11 '17 22:08

Mac


People also ask

How do you're-render the view when the browser is resized in React?

We can use the useLayoutEffect to add the event listener that runs when the window resizes. And in the window resize event handler, we can run our code to change a state to make the view rerender. We create the useWindowSize hook that has the size state.

What happens when the window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

When Rerendering happens in React?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.


2 Answers

When you change the window size - the size of the h1 element will not necessary change, so it isn't guaranteed that your code will run.

What you can do is use the DOM event of resize on the window element to call your function:

class Welcome extends React.Component {
    constructor() {
        super();
        this.state = {
          WindowSize : window.innerWidth
        }
        this.handleResize = this.handleResize.bind(this);
    }
    componentDidMount() {
      window.addEventListener("resize", this.handleResize);
    }
    componentWillUnmount() {
      window.addEventListener("resize", null);
    }
    handleResize(WindowSize, event) {
        this.setState({WindowSize: window.innerWidth})
    }
    render() {
    return <h1 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>
like image 186
Dekel Avatar answered Sep 23 '22 09:09

Dekel


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;
like image 33
Mamunur Rashid Avatar answered Sep 26 '22 09:09

Mamunur Rashid