Skip to content

Instantly share code, notes, and snippets.

@michaelgmcd
Created August 10, 2015 22:04
Show Gist options
  • Save michaelgmcd/9e73f2e1ae2065b8ee25 to your computer and use it in GitHub Desktop.
Save michaelgmcd/9e73f2e1ae2065b8ee25 to your computer and use it in GitHub Desktop.
Sticky navbar in React.js
var React = require('react');
var ExecutionEnvironment = require('react/lib/ExecutionEnvironment');
var cx = require('classnames');
var Nav = React.createClass({
componentDidMount: function() {
if (ExecutionEnvironment.canUseDOM) {
window.addEventListener('scroll', this.handleScroll, false);
}
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
getInitialState: function() {
return {
hidden: true
};
},
render: function() {
var navClasses = cx({
'nav': true,
'hidden': this.state.hidden
});
return (
<div className={navClasses} ref="navRef">
<div className="nav-inner">
</div>
</div>
);
},
handleScroll: function() {
// Navbar is 60px in height. Could also get height of DOM node here using
// findDOMNode(this.refs.navRef) and subtract that.
var heightToShow = window.innerHeight - 60;
if (window.pageYOffset > heightToShow) {
this.setState({ hidden: false });
}
if (window.pageYOffset < heightToShow) {
this.setState({ hidden: true });
}
}
});
module.exports = Nav;
@andyfaizan
Copy link

Thanks!

@vinayakhumberi
Copy link

Thanks..!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment