Skip to content

Instantly share code, notes, and snippets.

@vcarl

vcarl/visible-hoc.cjsx

Last active Aug 25, 2016
Embed
What would you like to do?
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