From d926b40d4ebbb799aca2c696a7d8e115ab1a626b Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Thu, 28 Nov 2024 17:23:41 +0100 Subject: [PATCH] build legacy root in React 16/17 --- src/renderWithoutAct.tsx | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/renderWithoutAct.tsx b/src/renderWithoutAct.tsx index c8826447f..e707e4052 100644 --- a/src/renderWithoutAct.tsx +++ b/src/renderWithoutAct.tsx @@ -1,4 +1,5 @@ import * as ReactDOMClient from 'react-dom/client' +import * as ReactDOM from 'react-dom' import { getQueriesForElement, prettyDOM, @@ -96,7 +97,11 @@ export type RenderWithoutActAsync = { | Omit | undefined, ): Promise< - RenderResult + RenderResult< + SyncQueries, + ReactDOMClient.Container, + ReactDOMClient.Container + > > } @@ -141,8 +146,11 @@ export function renderWithoutAct( let root: ReturnType // eslint-disable-next-line no-negated-condition -- we want to map the evolution of this over time. The root is created first. Only later is it re-used so we don't want to read the case that happens later first. if (!mountedContainers.has(container)) { - root = createConcurrentRoot(container) - + root = ( + ReactDOM.version.startsWith('16') || ReactDOM.version.startsWith('17') + ? createLegacyRoot + : createConcurrentRoot + )(container) mountedRootEntries.push({container, root}) // we'll add it to the mounted containers regardless of whether it's actually // added to document.body so the cleanup method works regardless of whether @@ -162,6 +170,17 @@ export function renderWithoutAct( return renderRoot(ui, {baseElement, container, queries, wrapper, root: root!}) } +function createLegacyRoot(container: ReactDOMClient.Container) { + return { + render(element: React.ReactNode) { + ReactDOM.render(element as unknown as React.ReactElement, container) + }, + unmount() { + ReactDOM.unmountComponentAtNode(container) + }, + } +} + function createConcurrentRoot(container: ReactDOMClient.Container) { const root = withDisabledActEnvironment(() => ReactDOMClient.createRoot(container),