Skip to content

Commit

Permalink
Prevents body scroll when Dialog is open (#3547)
Browse files Browse the repository at this point in the history
* prevents body scroll when the dialog is open

* Create tidy-melons-type.md

* updates changset

* keeps track of body overflow style to re-set it on unmount
  • Loading branch information
mperrotti authored Jul 26, 2023
1 parent 6c9c3df commit 7ef802e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .changeset/tidy-melons-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@primer/react": patch
---

Prevents body scroll when Dialog (the newer Dialog) is open

<!-- Changed components: Dialog -->
16 changes: 16 additions & 0 deletions src/Dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,22 @@ const _Dialog = React.forwardRef<HTMLDivElement, React.PropsWithChildren<DialogP
[onClose],
)

React.useEffect(() => {
const bodyOverflowStyle = document.body.style.overflow || ''
// If the body is already set to overflow: hidden, it likely means
// that there is already a modal open. In that case, we should bail
// so we don't re-enable scroll after the second dialog is closed.
if (bodyOverflowStyle === 'hidden') {
return
}

document.body.style.overflow = 'hidden'

return () => {
document.body.style.overflow = bodyOverflowStyle
}
}, [])

const header = (renderHeader ?? DefaultHeader)(defaultedProps)
const body = (renderBody ?? DefaultBody)(defaultedProps)
const footer = (renderFooter ?? DefaultFooter)(defaultedProps)
Expand Down

0 comments on commit 7ef802e

Please sign in to comment.