Reputation: 291
I am making a grid using divs in React. My Main
component has a Settings
component and a Boxes
component.
Changing the value inside Settings
will update a state value inside Main
, which is passed to Boxes
. Updating this value inside Settings
will cause Boxes
to rerender because it uses the state value of Main
.
Since the amount of boxes doesn't change, I would like to only change the width and height of each individual box with JavaScript. Re rendering isn't necessary in this case.
I've tried to implement my width/height changing code in shouldComponentUpdate
but this makes it so the boxes don't render at all and throws this error: Warning: Boxes.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.
So my question is: how can i keep these boxes rendered without having to re render, since updating the column count will only change width and height of each box?
Current implementation of shouldComponentUpdate:
shouldComponentUpdate() {
let boxSize = this.state.wrapperWidth / this.props.columns;
document.styleSheets[1].cssRules[0].style.setProperty('width', boxSize+"px", null);
document.styleSheets[1].cssRules[0].style.setProperty('height', boxSize+"px", null);
}
Upvotes: 1
Views: 698
Reputation: 6299
Whenever a component receives props, it will render again. So when the state of your Main
component is changed, it will trigger a render of Main
which will inevitably pass props to Boxes
and will trigger a render.
However you can use PureCompoonent
to prevent rendering a component if the new props it received is the same as old props.
PureComponent does a shallow comparison of previous props and prevents re-render if the props are not changed.
import React, { PureComponent } from 'react';
class Boxes extends PureComponent {
... your commponent code
}
You can read more on PureComponent here - Official React Docs - PureComponent
Upvotes: 1