From be22909d809666da1e7efe6428a500e1f4f76933 Mon Sep 17 00:00:00 2001 From: Mantas Kantautas Date: Fri, 23 Oct 2026 03:53:05 +0300 Subject: [PATCH] fix: Avoid `cleanup` error when the container is `document` --- src/__tests__/cleanup.js | 40 ++++++++++++++++++++++++++++++++++++++++ src/pure.js | 3 ++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/__tests__/cleanup.js b/src/__tests__/cleanup.js index 9f17c722..649a34e8 100644 --- a/src/__tests__/cleanup.js +++ b/src/__tests__/cleanup.js @@ -27,6 +27,46 @@ test('cleanup does not error when an element is not a child', () => { cleanup() }) +describe('container is the document', () => { + let documentElement + beforeEach(() => { + documentElement = document.documentElement + }) + + afterEach(() => { + // React 18 removes the `` element when unmounting a root rendered into `document` + if (document.documentElement === null) { + document.appendChild(documentElement) + } + }) + + test('cleanup does not error when the container is the document', () => { + render( + + +
+ + , + {container: document}, + ) + + cleanup() + }) + + test('cleanup does not error when hydrating the document', () => { + render( + // eslint-disable-next-line jsx-a11y/html-has-lang -- matches the existing document + + + + , + {container: document, hydrate: true}, + ) + + cleanup() + }) +}) + test('cleanup runs effect cleanup functions', () => { const spy = jest.fn() diff --git a/src/pure.js b/src/pure.js index 3ea36bfe..c745c855 100644 --- a/src/pure.js +++ b/src/pure.js @@ -319,7 +319,8 @@ function cleanup() { act(() => { root.unmount() }) - if (container.parentNode === document.body) { + // `document.body` is `null` if unmounting a root rendered into `document` removed `` (React 18) + if (document.body !== null && container.parentNode === document.body) { document.body.removeChild(container) } })