Skip to content

Instantly share code, notes, and snippets.

@mimiflynn
Forked from julianocomg/AffixWrapper.jsx
Last active January 17, 2017 21:03
Show Gist options
  • Save mimiflynn/749afd1fe0204ea8b7e8 to your computer and use it in GitHub Desktop.
Save mimiflynn/749afd1fe0204ea8b7e8 to your computer and use it in GitHub Desktop.
A simple affix React component.
/**
* @author Juliano Castilho <julianocomg@gmail.com>
* ES6 conversion by mimi.flynn@effectiveui.com
*/
import React from 'react';
import ClassNames from 'classnames';
class AffixWrapper extends React.Component {
constructor() {
super();
this.state = {
affix: false
};
this.handleScroll = this.handleScroll.bind(this);
}
/**
* @return {void}
*/
handleScroll() {
var affix = this.state.affix;
var offset = this.props.offset;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (!affix && scrollTop >= offset) {
this.setState({
affix: true
});
}
if (affix && scrollTop < offset) {
this.setState({
affix: false
});
}
}
/**
* @return {void}
*/
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
this.handleScroll();
}
/**
* @return {void}
*/
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
render() {
var affix = this.state.affix ? 'affix' : '';
var {className, offset } = this.props;
return (
<div className={ClassNames(className, affix)}>
{this.props.children}
</div>
);
}
}
AffixWrapper.propTypes = {
offset: React.PropTypes.number
};
export default AffixWrapper;
<AffixWrapper className="some-cool-element" id="lalala" offset={200}>
<div>Put whatever you want here</div>
</AffixWrapper>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment