Last active
May 17, 2024 04:24
-
-
Save julianocomg/296469e414db1202fc86 to your computer and use it in GitHub Desktop.
A simple affix React component.
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
/** | |
* @author Juliano Castilho <[email protected]> | |
*/ | |
var React = require('react'); | |
var AffixWrapper = React.createClass({ | |
/** | |
* @type {Object} | |
*/ | |
propTypes: { | |
offset: React.PropTypes.number | |
}, | |
/** | |
* @return {Object} | |
*/ | |
getDefaultProps() { | |
return { | |
offset: 0 | |
}; | |
}, | |
/** | |
* @return {Object} | |
*/ | |
getInitialState() { | |
return { | |
affix: false | |
}; | |
}, | |
/** | |
* @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); | |
}, | |
/** | |
* @return {void} | |
*/ | |
componentWillUnmount() { | |
window.removeEventListener('scroll', this.handleScroll); | |
}, | |
render() { | |
var affix = this.state.affix ? 'affix' : ''; | |
var {className, offset, ...props} = this.props; | |
return ( | |
<div {...props} className={className + ' ' + affix)}> | |
{this.props.children} | |
</div> | |
); | |
} | |
}); | |
module.exports = AffixWrapper; |
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
<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
A functional component with react hook alternative that preserve the width