Created
February 7, 2018 17:45
-
-
Save kyle-mccarthy/b9c0239c0d90be3b02fab6d654adf871 to your computer and use it in GitHub Desktop.
React locking of body scroll for desktop and touch devices
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
import React from 'react'; | |
const withScrolllock = (WrappedComponent) => { | |
return class ScrolllockComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.y = null; | |
this.ref = null; | |
} | |
lock = (ref) => { | |
this.ref = ref; | |
this._addListeners(); | |
document.body.classList.add('no-scroll'); | |
} | |
unlock = (ref) => { | |
this.ref = ref; | |
this._removeListeners(); | |
document.body.classList.remove('no-scroll'); | |
} | |
_addListeners = () => { | |
this.ref.addEventListener('touchstart', this._handleTouchStart, false); | |
this.ref.addEventListener('touchmove', this._handleTouchMove, false); | |
} | |
_handleTouchStart = (event) => { | |
if (event.targetTouches.length === 1) { | |
// detect single touch | |
this.y = event.targetTouches[0].clientY; | |
} | |
} | |
_handleTouchMove = (event) => { | |
if (event.targetTouches.length === 1) { | |
// detect single touch | |
this.disableRubberBand(event); | |
} | |
} | |
_removeListeners = () => { | |
this.ref.removeEventListener('touchstart', this._handleTouchStart); | |
this.ref.removeEventListener('touchmove', this._handleTouchMove); | |
} | |
disableRubberBand = (event) => { | |
let clientY = event.targetTouches[0].clientY - this.y; | |
if (this.ref.scrollTop === 0 && clientY > 0) { | |
// element is at the top of its scroll | |
event.preventDefault(); | |
} | |
if (this.isOverlayTotallyScrolled() && clientY < 0) { | |
//element is at the top of its scroll | |
event.preventDefault(); | |
} | |
} | |
isOverlayTotallyScrolled = () => { | |
return this.ref.scrollHeight - this.ref.scrollTop <= this.ref.clientHeight; | |
} | |
render() { | |
return (<WrappedComponent {...this.props} lock={this.lock} unlock={this.unlock} />) | |
} | |
} | |
} | |
export { withScrolllock }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment