Skip to content

Instantly share code, notes, and snippets.

@timc1
Created April 24, 2019 02:15
Show Gist options
  • Save timc1/d92698c7317c3d01a9612b062c3fecb1 to your computer and use it in GitHub Desktop.
Save timc1/d92698c7317c3d01a9612b062c3fecb1 to your computer and use it in GitHub Desktop.
Prevent overflow scrolling — nice to use when displaying a modal
const capturePosition = () => {
const cachedPosition = window.pageYOffset
return {
freeze: () => {
document.body.style =
`position: fixed;
top: ${cachedPosition * -1}px;
width: 100%;`
},
unfreeze: () => {
document.body.removeAttribute('style')
window.scrollTo({
top: cachedPosition,
})
},
}
}
@timc1
Copy link
Author

timc1 commented Apr 24, 2019

Example:

const { freeze, unfreeze } = capturePosition()

React.useEffect(() => {
  if (state.isModalShowing) {
    freeze()
  }
  return () => {
    if (state.isModalShowing) unfreeze()
  } 
}, [state.isModalShowing])

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