Created
October 16, 2018 17:36
-
-
Save hypervillain/295bfe7866702b281433e227fecd8d8e to your computer and use it in GitHub Desktop.
A generic React component that forwards document's scroll Y and X positions
This file contains hidden or 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
// See it in action here: https://codesandbox.io/s/ovyk4qx8yy | |
import React, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
class ForwardScroll extends Component { | |
static propTypes = { | |
children: PropTypes.func.isRequired, | |
ComponentWrapper: PropTypes.node || PropTypes.string, | |
} | |
static defaultProps = { | |
ComponentWrapper: 'div', | |
} | |
constructor(props) { | |
super(props); | |
this.state = { | |
scrollY: 0, | |
scrollX: 0, | |
}; | |
this.handleScroll = this.handleScroll.bind(this); | |
} | |
componentDidMount() { | |
window.addEventListener('scroll', this.handleScroll, { passive: true }); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('scroll', this.handleScroll); | |
} | |
handleScroll() { | |
this.setState({ | |
scrollY: window.pageYOffset || document.documentElement.scrollTop, | |
scrollX: window.pageXOffset || document.documentElement.scrollLeft, | |
}); | |
} | |
render() { | |
const { children, ComponentWrapper, ...rest } = this.props; | |
return ( | |
<ComponentWrapper {...rest}> | |
{children({ scrollY: this.state.scrollY, scrollX: this.state.scrollX })} | |
</ComponentWrapper> | |
); | |
} | |
} | |
ForwardScroll.displayName = 'ForwardScroll'; | |
export default ForwardScroll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment