Last active
August 25, 2016 19:36
-
-
Save vcarl/1bd362d345bb698016f9 to your computer and use it in GitHub Desktop.
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
define (require) -> | |
_ = require('lodash') | |
React = require('react') | |
ReactDOM = require('react-dom') | |
# Modified from http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport | |
isElementInViewport = (el) -> | |
rect = el.getBoundingClientRect(); | |
( | |
rect.bottom >= 0 and | |
rect.right >= 0 and | |
rect.top <= (window.innerHeight or document.documentElement.clientHeight) and | |
rect.left <= (window.innerWidth or document.documentElement.clientWidth) | |
) | |
(Component) -> | |
React.createClass | |
displayName: 'Visible' | |
getInitialState: -> | |
isVisible: false | |
componentWillMount: -> | |
# Throttle the event handler since it's on scroll. | |
@_handleScroll = _.throttle(@_handleScroll) | |
window.addEventListener('scroll', @_handleScroll) | |
componentDidMount: -> | |
@_handleScroll() | |
componentWillUnmount: -> | |
window.removeEventListener('scroll', @_handleScroll) | |
_handleScroll: -> | |
# Only set state if the value changed, avoiding unnecessary renders. | |
isVisible = isElementInViewport(ReactDOM.findDOMNode(@)) | |
if isVisible isnt @state.isVisible | |
@setState(isVisible: isVisible) | |
render: -> | |
# Pass all props and state down to the component passed in. | |
<Component {...@props} {...@state} /> | |
## Usage: | |
# Visible = require('./visible.cjsx') | |
# Comp = React.createClass({...}) | |
# Visible(Comp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment