I have a stateful component which has a scroll event listener like this
import React, { Component } from 'react'
import { withRouter } from 'react-router'
import AppDetailPageUI from './AppDetailPageUI.js'
class AppDetailPageSF extends Component {
constructor(props) {
super(props);
this.state = {
scrolledDown:false,
};
this.handleScroll = this.handleScroll.bind(this);
}
render() {
return (
<AppDetailPageUI
scrolledDown={this.state.scrolledDown}
/>
);
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
if (window.scrollY === 0 && this.state.scrolledDown === true) {
this.setState({scrolledDown: false});
}
else if (window.scrollY !== 0 && this.state.scrolledDown !== true) {
this.setState({scrolledDown: true});
}
}
}
export default withRouter(AppDetailPageSF)
This works perfectly fine.But i want to use handleScroll method in many statefull components, and including the same method in every component is not a good practice.
so this is what i tried instead, I created another HandleScrollUtil function something like this
const HandleScrollUtil = {
handleScroll: function(component) {
if (window.scrollY === 0 && component.state.scrolledDown === true) {
component.setState({scrolledDown: false});
}
else if (window.scrollY !== 0 && component.state.scrolledDown !== true) {
component.setState({scrolledDown: true});
}
}
}
export default HandleScrollUtil
and then i tried calling this method by passing this reference something like this
componentDidMount() {
window.addEventListener('scroll', HandleScrollUtil.handleScroll(this));
}
componentWillUnmount() {
window.removeEventListener('scroll', HandleScrollUtil.handleScroll(this));
}
But it does not seem to work now.