Created
April 27, 2019 13:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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