mikejw mikejw - 2 months ago 20
Javascript Question

Simple window resize react

I'm attempting to capture the window height and pass it to child components in react.

I'm referring to this guide from the manual: https://facebook.github.io/react/tips/dom-event-listeners.html.

This is how my code is looking but I'm getting a 'setState is not a function' error.

import React from 'react';
import jsonp from 'jsonp';
import Gallery from './Gallery.jsx';

export const MF = 'http://auryn/modern-frontend/public_html';

export default class App extends React.Component {

constructor(props) {
super(props);

this.state = {
images: [ 'DSCF1176.jpg' ],
height: window.innerHeight+'px'
};
var self = this;

// get images
var url = MF+'/api/posts';
jsonp(url, {}, function (err, data) {
const blogs = data.data.blogs.map(item => {
return {
'images': item.image
}
});
var images = [];
blogs.forEach(b => {
b.images.forEach(i => {
images.push(i.filename);
});
});
//console.log(JSON.stringify(images));
//self.images = images;
self.setState({ images });
});
}

componentDidMount() {
window.addEventListener('resize', this.handleResize);
}

handleResize(e) {
this.setState({height: window.innerHeight+'px'});
}

componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}

render() {
return (
<Gallery images={this.state.images} height={this.state.height} />
);
}
}

Answer

Your handleResize function's body will get the window context. You can bind it to your component class in constructor :

constructor(){
  ...
  this.handleResize = this.handleResize.bind(this);
  ...
}
Comments