Skip to content

Commit

Permalink
Ensure portal root exists in the DOM (#950)
Browse files Browse the repository at this point in the history
* ensure that the portal root is always in the DOM

When using NextJS, it happens that between page transitions the portal
root gets removed form the DOM. We will check the DOM when the `target`
updates, and if it doesn't exist anymore, then we will re-insert it in
the DOM.

* update changelog
  • Loading branch information
RobinMalfait authored Nov 23, 2021
1 parent 50d9fd3 commit 8c57814
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased - React]

- Nothing yet!
### Fixes

- Ensure portal root exists in the DOM ([#950](https://github.com/tailwindlabs/headlessui/pull/950))

## [Unreleased - Vue]

Expand Down
9 changes: 9 additions & 0 deletions packages/@headlessui-react/src/components/portal/portal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ function usePortalTarget(): HTMLElement | null {
return document.body.appendChild(root)
})

// Ensure the portal root is always in the DOM
useEffect(() => {
if (target === null) return

if (!document.body.contains(target)) {
document.body.appendChild(target)
}
}, [target])

useEffect(() => {
if (forceInRoot) return
if (groupTarget === null) return
Expand Down

0 comments on commit 8c57814

Please sign in to comment.