I am animating several React.js components based on their position in the viewport. If the component is in the viewport, animate the opacity to 1, if it\'s not in the viewpo
Here is a simpler code snippet that should work as required. You are missing the this binding, as such, when you execute window.addEventListener('scroll', this.handleScroll); you are actually pointing this to the window object.
Instead you will need to bind this in the constructor. Hope it
class Home extends Component {
constructor(props) {
super(props)
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(e) {
console.log('scroll event');
console.log(e);
}
render() {
return (
);
}
}
Another option is the below, both options should work :)
class Home extends Component {
componentDidMount() {
window.addEventListener('scroll', this.handleScroll.bind(this));
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll.bind(this));
}
handleScroll(e) {
console.log('scroll event');
console.log(e);
}
render() {
return (
);
}
}