Skip to content

Instantly share code, notes, and snippets.

@effe-megna
Created April 27, 2019 13:49
Show Gist options
  • Save effe-megna/36306cff5588a205ca35f51829d518da to your computer and use it in GitHub Desktop.
Save effe-megna/36306cff5588a205ca35f51829d518da to your computer and use it in GitHub Desktop.
An High-ordered component for detect when the user is at the top of the page
export const withTopDetector = Component => {
return class extends React.Component {
state = {
isAtTop: true
};
componentDidMount() {
window.addEventListener("scroll", this.onScrollListener);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.onScrollListener);
}
onScrollListener = () => {
const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = winScroll / height;
this.setState({ isAtTop: scrolled === 0 });
};
render() {
const { isAtTop } = this.state;
return (
<Component
isAtTop={isAtTop}
/>
)
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment