Created
September 17, 2018 08:58
-
-
Save hadnazzar/487323a7ba0434c433b2c3b23695e500 to your computer and use it in GitHub Desktop.
Sticky element in react
This file contains 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
--- | |
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