Reputation: 27
I'm trying a pretty easy thing with react, namely a display of the current browser width. It works just fine when loading the page, but it doesn't update on resizing for some reason, even though I appear to update the state... Help?
import React from "react";
class SmartBr extends React.Component {
constructor() {
super();
this.state = {
WindowWidth:
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth,
WindowHeight:
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight
};
}
updateDimensions() {
this.setState = {
WindowWidth:
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth,
WindowHeight:
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight
};
}
/**
* Add event listener
*/
componentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions.bind(this));
}
/**
* Remove event listener
*/
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this));
}
render() {
return <p>{this.state.WindowWidth}</p>;
}
}
export default SmartBr;
Upvotes: 1
Views: 277
Reputation: 12796
setState
outside of the constructor is a function you call, not an object you set to it, so you need to change your updateDimensions
function to call the setState
method, and not assign an object as you are doing now :)
updateDimensions() {
this.setState({
WindowWidth:
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth,
WindowHeight:
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight
});
}
Upvotes: 3