Jak111
Jak111

Reputation: 119

React update on window resize

I have created a grid with some images and want to update the number of columns on certain widths. For example:

I've created a function to update the number of rows, but how can I rerender the grid without pressing F5?

My states:

this.state = {
  numberOfColumns: 3,
  breakpointSm: 660px,
  breakpointMd: 960px,
};

My function:

getNumberOfColumns(){
  let smallDevices = window.matchMedia( "(max-width: " + this.state.breakpointSm + ")" );
  let mediumDevices = window.matchMedia( "(max-width:" + this.state.breakpointMd + ")" );
  let columns;

  if (smallDevices.matches) {
    columns = 1;
  } else if (mediumDevices.matches){
    columns = 2;
  } else {
    columns = 3;
  }
  this.setState({
    numberOfColumns: columns
  });
}

Component will mount:

componentWillMount() {
  this.getNumberOfColumns();
}

Upvotes: 0

Views: 6663

Answers (2)

Piotr
Piotr

Reputation: 31

I would advice using CSS for it, it approach seems more approprate for me. Re-rendering component to do something that can be achieved with media queries in CSS is an overkill IMHO.

CSS:

//for medium screens
.container {
    display: grid;
    grid-template-rows: 1fr 1fr;
    grid-template-columns: auto;
    //for tiny screens
    @media screen and (max-width: 660px) {
        grid-template-rows: 1fr;
    }
    //for big screens
    @media screen and (min-width: 960px) {
        grid-template-rows: 1fr 1fr 1fr;
   }
}

Upvotes: 1

Abslen Char
Abslen Char

Reputation: 3135

a simple way to slove the issue is to added an event listner on resize or simply use a plain css what this code actually do is to force a re-render every time the window size change

    getNumberOfColumns() {
        let columns;
        if(window.innerWidth === this.state.breakpointSm) {
          columns = 1;
        } else if(window.innerWidth === this.state.breakpointMd) {
         columns = 2;

        }else{
       columns = 3;
             }
         this.setState({
             numberOfColumns: columns
                    });
      }


componentDidMount() {
  this.getNumberOfColumns();
window.addEventListener("resize", this.getNumberOfColumns.bind(this));
}

 componentWillUnmount() {
    window.removeEventListener("resize", this.getNumberOfColumns.bind(this));
  }

and in the worst case scenario if nothing work , you can use this.forceUpdate() but try to avoid it as much as you can

i didnt test it yet , but i hope this will help

Upvotes: 2

Related Questions