Reputation: 193
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} />
);
}
}
Upvotes: 0
Views: 729
Reputation: 7308
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);
...
}
Upvotes: 2
Reputation: 2835
You can't access the Component's attributes or functions from a different Context (in this case the Callback). You need to bind your Callback function if you need to use your component as the Context, the function should look like this:
jsonp(url, {}, function (err, data) {
// your code
this.setState({ images });
}.bind(this));
Same goes for your handlesize
function.
Upvotes: 0