Reputation: 1090
Here is my component code. Everything is working successfully except this 'onResize' function.
class MyComponent extends Component {
constructor(props) {
super(props)
this.onResize = this.onResize.bind(this)
}
onResize = () => {
window.onresize = () => {
alert(true)
//I had tried with 'this.alert(true)' too
}
}
}
componentDidMount() {
this.onResize()
}
//rest of the code ommited
Upvotes: 0
Views: 305
Reputation: 3887
You need to add an event listener for the resize
onResize() {
this.setState({
width: $(window).width(),
height: $(window).height()
})
}
componentWillMount() {
this.onResize();
}
componentDidMount() {
window.addEventListener("resize", this.onResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.onResize);
}
Upvotes: 0
Reputation: 3725
You have to add an event listener in the componentDidMount
lifecycle:
componentDidMount() {
window.addEventListener('resize', this.handleWindowResize)
}
Remember to remove the event listener when you unmount the component to avoid memory leaks:
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowResize)
}
Upvotes: 2