Skip to content

Instantly share code, notes, and snippets.

@simonkberg
Created June 22, 2017 08:18
Show Gist options
  • Save simonkberg/c9e8068ac3d51107a14e4d8f5b37c77b to your computer and use it in GitHub Desktop.
Save simonkberg/c9e8068ac3d51107a14e4d8f5b37c77b to your computer and use it in GitHub Desktop.
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