Skip to content

Commit

Permalink
do react 18 checks for create root/ render
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinjude committed Jun 27, 2022
1 parent a8c2a9b commit e3f2571
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions packages/gatsby/cache-dir/page-renderer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* global HAS_REACT_18 */
import React, { createElement, useEffect } from "react"
import { createRoot } from "react-dom/client"
import PropTypes from "prop-types"
import { apiRunner } from "./api-runner-browser"
import { grabMatchParams } from "./find-path"
Expand All @@ -15,6 +15,17 @@ function Caller({ children, callback }) {
return children
}

// TODO: We do something similar in production-app, we should use a take this function, put it in some utils file and share
function render(el, Component) {
if (HAS_REACT_18) {
const reactDomClient = require(`react-dom/client`)
reactDomClient.createRoot(el).render(Component)
} else {
const reactDomClient = require(`react-dom`)
reactDomClient.render(Component, el)
}
}

// Renders page
function PageRenderer(props) {
const _props = {
Expand Down Expand Up @@ -51,7 +62,6 @@ function PageRenderer(props) {

useEffect(() => {
const hiddenRoot = document.createElement(`div`)
const root = createRoot(hiddenRoot)

const callback = () => {
// Remove previous head nodes
Expand Down Expand Up @@ -84,8 +94,10 @@ function PageRenderer(props) {

document.head.append(...validHeadNodes)
}

// Use react18's .createRoot.render or fallback to .render
// just a hack to call the callback after react has done first render
root.render(<Caller callback={callback}>{headElement}</Caller>)
render(hiddenRoot, <Caller callback={callback}>{headElement}</Caller>)
}, [headElement])
}
const wrappedPage = apiRunner(
Expand Down

0 comments on commit e3f2571

Please sign in to comment.