I'm building a photo gallery in react js. Obviously it's going to have to be responsive and I've tackled this by setting values like so in the component's render method:
let thumbWidth = window.innerWidth >= 480 ? 75 : 100;
The problem is that I need the const value to change when the window is resized. My my first attempts was to build a function like so and bind it in the constructor:
getThumbWidth = (vpWidth) => {
if(vpWidth >= 480 ) {
this.setState({thumbSize: 120});
} else {
this.setState({thumbSize: 50});
}
}
This worked in terms of setting the variable's initial value but how do I trigger the function when the window resizes?
Have tried adding a resize function:
resize = () => this.getThumbWidth()
...and then changing getThumbWidth so that it sets the value in the component's sate - the idea being that when state is updated the component automatically rerenders:
getThumbWidth = (vpWidth) => {
if(vpWidth >= 480 ) {
this.setState({thumbSize: 120});
} else {
this.setState({thumbSize: 50});
}
}
And then calling it via lifecycle methods as suggested in several other solutions but the event listener does not appear to be firing:
componentDidMount() {
window.addEventListener('resize', this.resize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize)
}
Still not working though... any ideas?
constant in the first place? Hint is in the name,constis constant - in other words, constant things do not change, they stay the same. Why not useletinstead - acts as a same block-scoped variable likeconstdoes, only the values can change.getThumbWidththere's a parameter but when you call it you don't pass this parameterresize = () => this.getThumbWidth()