Skip to content

Instantly share code, notes, and snippets.

@vcarl
Last active August 25, 2016 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vcarl/1bd362d345bb698016f9 to your computer and use it in GitHub Desktop.
Save vcarl/1bd362d345bb698016f9 to your computer and use it in GitHub Desktop.
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