Skip to content

Commit

Permalink
fix(gatsby,gatsby-plugin-image): fix createRoot on React 18 (#32378) (#…
Browse files Browse the repository at this point in the history
…32420)

Co-authored-by: Ward Peeters <ward@coding-tech.com>
  • Loading branch information
GatsbyJS Bot and wardpeet committed Jul 19, 2021
1 parent 0ae10bf commit 1b45c7b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
26 changes: 21 additions & 5 deletions packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx
@@ -1,5 +1,6 @@
import React, { MutableRefObject } from "react"
import { hydrate, render } from "react-dom"
// @ts-ignore - react 18 has createRoot
import { hydrate, render, createRoot } from "react-dom"
import { GatsbyImageProps } from "./gatsby-image.browser"
import { LayoutWrapper } from "./layout-wrapper"
import { Placeholder } from "./placeholder"
Expand Down Expand Up @@ -87,14 +88,29 @@ export function lazyHydrate(

if (root.current) {
// Force render to mitigate "Expected server HTML to contain a matching" in develop
const doRender = hydrated.current || forceHydrate.current ? render : hydrate
doRender(component, root.current)
hydrated.current = true
if (createRoot) {
if (!hydrated.current) {
hydrated.current = createRoot(root.current)
}

// @ts-ignore react 18 typings
hydrated.current.render(component)
} else {
const doRender =
hydrated.current || forceHydrate.current ? render : hydrate
doRender(component, root.current)
hydrated.current = true
}
}

return (): void => {
if (root.current) {
render((null as unknown) as ReactElement, root.current)
if (createRoot) {
// @ts-ignore react 18 typings
hydrated.current.render(null)
} else {
render((null as unknown) as ReactElement, root.current)
}
}
}
}
2 changes: 1 addition & 1 deletion packages/gatsby/cache-dir/app.js
Expand Up @@ -194,7 +194,7 @@ apiRunnerAsync(`onClientEntry`).then(() => {
document.body.append(indicatorMountElement)

if (renderer === ReactDOM.hydrateRoot) {
renderer(indicatorMountElement).render(
ReactDOM.createRoot(indicatorMountElement).render(
<LoadingIndicatorEventHandler />
)
} else {
Expand Down

0 comments on commit 1b45c7b

Please sign in to comment.