react-scroll-activator demo
by Mae Capozzi
HTML
<div id="app"></div>
CSS
@import url(//fonts.googleapis.com/css?family=Roboto:400,700,300);
React
// Scroll Activator Component
// This is what actually comes in the react-scroll-activator package
class ScrollActivator extends React.Component {
state = { activatedState: 'isNotActivated' }
componentDidMount(){
this.props.containerSelector
? this.setContainerSelector()
: this.setContainerSelectorToWindow()
this.containerSelector &&
this.containerSelector.addEventListener('scroll', this.handleScroll)
}
componentWillUnmount() {
this.containerSelector &&
this.containerSelector.removeEventListener('scroll', this.handleScroll)
}
setContainerSelector = () => {
this.containerSelector = document.querySelector(
this.props.containerSelector
)
}
setContainerSelectorToWindow = () => {
this.containerSelector = window
}
handleScroll = e => {
let activatedState = this.props.onScroll(e) ? 'isActivated' : 'isNotActivated'
if (this.state.activatedState != activatedState) {
this.setState({ activatedState })
}
}
render() {
return this.props.children(this.state.activatedState)
}
}
// This is a scrollable container component.
class Container extends React.Component {
// As a developer, you'll need to write your own function that you can pass into the ScrollActivator. This will determine what rules it will follow, and when it will pass the activatedState prop to the children.
handleScrollCallback = e => {
this.containerSelector = document.querySelector('.any-class-name')
return (
e.target.scrollTop >
this.containerSelector.getBoundingClientRect().top + 500
)
}
render () {
// Pass the callback you've written into onScroll, and the class name of the parent into containerSelector.
return (
<div style={styleObj} className='any-class-name'>
<ScrollActivator
onScroll={this.handleScrollCallback}
containerSelector='.any-class-name'
>
{activatedState => <StickyElement...