Created
May 1, 2015 17:26
-
-
Save dallonf/3f365373ae971d278706 to your computer and use it in GitHub Desktop.
React FloatingElement
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
var FloatingElement = React.createClass({ | |
propTypes: { | |
children: React.PropTypes.element.isRequired, | |
floatingClassName: React.PropTypes.string | |
}, | |
getDefaultProps() { | |
return { | |
floatingClassName: 'floating' | |
}; | |
}, | |
getInitialState() { | |
return { | |
float: false | |
}; | |
}, | |
render() { | |
return ( | |
<div> | |
<div ref="container"> | |
{this.props.children} | |
</div> | |
{this.state.float && | |
this.renderFloatingChild() | |
} | |
</div> | |
); | |
}, | |
renderFloatingChild() { | |
var child = this.props.children; | |
var classes = child.props.className + ' ' + this.props.floatingClassName; | |
return React.cloneElement(child, {className: classes}); | |
}, | |
componentDidMount() { | |
$(window).on('resize scroll', this.handleReflow); | |
this.handleReflow(); | |
}, | |
componentWillUnmount() { | |
$(window).off('resize scroll', this.handleReflow); | |
}, | |
componentDidUpdate() { | |
this.handleReflow(); | |
}, | |
handleReflow(e) { | |
var $window = $(window); | |
var $container = $(React.findDOMNode(this.refs.container)); | |
var windowBottom = $window.scrollTop() + $window.height(); | |
var containerBottom = $container.offset().top + $container.outerHeight(); | |
var float = windowBottom < containerBottom; | |
if (this.state.float !== float) { | |
this.setState({float}); | |
} | |
} | |
}); | |
export default FloatingElement; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment