Unverified Commit ce6e8b56 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

fix: react root enabled properly in custom server (#36664)

Fixes #36643

## Bug

* hoist react dom choosing in client
* also assign __NEXT_REACT_ROOT env in custom server

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
parent 9cda84b4
/* global location */
import '../build/polyfills/polyfill-module'
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import { HeadManagerContext } from '../shared/lib/head-manager-context'
import mitt, { MittEmitter } from '../shared/lib/mitt'
import { RouterContext } from '../shared/lib/router-context'
......@@ -41,6 +40,10 @@ import { RefreshContext } from './streaming/refresh'
import { ImageConfigContext } from '../shared/lib/image-config-context'
import { ImageConfigComplete } from '../shared/lib/image-config'
const ReactDOM = process.env.__NEXT_REACT_ROOT
? require('react-dom/client')
: require('react-dom')
/// <reference types="react-dom/experimental" />
declare let __webpack_public_path__: string
......@@ -549,8 +552,7 @@ function renderReactElement(
if (process.env.__NEXT_REACT_ROOT) {
if (!reactRoot) {
// Unlike with createRoot, you don't need a separate root.render() call here
const ReactDOMClient = require('react-dom/client')
reactRoot = ReactDOMClient.hydrateRoot(domEl, reactEl)
reactRoot = ReactDOM.hydrateRoot(domEl, reactEl)
// TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing
shouldHydrate = false
} else {
......
......@@ -183,6 +183,14 @@ function createServer(options: NextServerOptions): NextServer {
)
}
// Make sure env of custom server is overridden.
// Use dynamic require to make sure it's executed in it's own context.
const ReactDOMServer = require('react-dom/server.browser')
const shouldUseReactRoot = !!ReactDOMServer.renderToReadableStream
if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
return new NextServer(options)
}
......
......@@ -132,8 +132,18 @@ describe('Custom Server', () => {
try {
browser = await webdriver(context.appPort, '/test-index-hmr')
const text = await browser.elementByCss('#go-asset').text()
const logs = await browser.log()
expect(text).toBe('Asset')
// Hydrates with react 18 is correct as expected
expect(
logs.some((log) =>
log.message.includes(
'ReactDOM.hydrate is no longer supported in React 18'
)
)
).toBe(false)
indexPg.replace('Asset', 'Asset!!')
await check(() => browser.elementByCss('#go-asset').text(), /Asset!!/)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment