Created
June 22, 2017 08:18
-
-
Save simonkberg/c9e8068ac3d51107a14e4d8f5b37c77b to your computer and use it in GitHub Desktop.
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
import React, { Component } from 'react' | |
import classNames from 'classnames' | |
import styles from './Styles.css' | |
// Constant with scroll offset to trigger sticky | |
const SCROLL_OFFSET = 100 | |
class ComponentThatNeedsScrollHandling extends Component { | |
state = { sticky: false } | |
ticking = false | |
over = false | |
scrollTop = 0 | |
componentDidMount() { | |
document.addEventListener('scroll', this.onScroll, { passive: true }) | |
} | |
componentWillUnmount() { | |
document.removeEventListener('scroll', this.onScroll) | |
} | |
onScroll = event => { | |
this.scrollTop = event.scrollY | |
if (!this.ticking) { | |
window.requestAnimationFrame(this.checkScrollPos) | |
} | |
this.ticking = true | |
} | |
checkScrollPos = () => { | |
if (over && this.scrollTop < SCROLL_OFFSET) { | |
this.setState({ sticky: false }) | |
} else if (!over && this.scrollTop > SCROLL_OFFSET) { | |
this.setState({ sticky: true }) | |
} | |
} | |
render() { | |
const className = classNames(styles.thing, { | |
[styles.isSticky]: this.state.sticky, | |
}) | |
return <div className={className} /> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment