Skip to content

Instantly share code, notes, and snippets.

@hadnazzar
Created September 17, 2018 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadnazzar/487323a7ba0434c433b2c3b23695e500 to your computer and use it in GitHub Desktop.
Save hadnazzar/487323a7ba0434c433b2c3b23695e500 to your computer and use it in GitHub Desktop.
Sticky element in react
---
jsx
---
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = (event) => {
const el = document.querySelector('#formSidebar');
console.log(this.stickyBar.getBoundingClientRect());
const top = this.stickyBar.getBoundingClientRect().top;
if (top < 0) {
console.log('above');
if (!this.state.stickyEnabled) {
this.setState({ stickyEnabled: true });
}
} else {
console.log('below');
if (this.state.stickyEnabled) {
this.setState({ stickyEnabled: false });
}
}
}
---
html - jsx
---
<section className="isolated" ref={ (stickyBar) => { this.stickyBar = stickyBar; } }>
<div className={ this.state.stickyEnabled ? 'sticky-element' : '' }>
</div>
<section>
---
style.css
---
.sticky-element{
position: fixed;
top: 0;
margin-top: 0;
z-index: 9;
width: 283px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment