Support document rendering (#24523)

* Support Document as a container for hydration and rendering

Previously Document was not handled effectively as a container. in particual when hydrating if there was a fallback to client rendering React would attempt to append a new <html> element into the document before clearing out the existing one which errored leaving the application in brokent state.

The initial approach I took was to recycle the documentElement and never remove or append it, always just moving it to the right fiber and appending the right children (heady/body) as needed. However in testing a simple approach in modern browsers it seems like treating the documentElement like any other element works fine. This change modifies the clearContainer method to remove the documentElement if the container is a DOCUMENT_NODE. Once the container is cleared React can append a new documentElement via normal means.

* Allow Document as container for createRoot

previously rendering into Document was broken and only hydration worked because React did not properly deal with the documentElement and would error in a broken state if used that way. With the previous commit addressing this limitation this change re-adds Document as a valid container for createRoot.

It should be noted that if you use document with createRoot it will drop anything a 3rd party scripts adds the page before rendering for the first time.
This commit is contained in:
Josh Story 2022-05-10 10:17:36 -07:00 committed by GitHub
parent d20c3af9d1
commit 8197c73ec3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 5 additions and 6 deletions

View File

@ -23,7 +23,7 @@ import {
} from './';
export function createRoot(
container: Element | DocumentFragment,
container: Element | Document | DocumentFragment,
options?: CreateRootOptions,
): RootType {
if (__DEV__) {

View File

@ -148,7 +148,7 @@ const Internals = {
};
function createRoot(
container: Element | DocumentFragment,
container: Element | Document | DocumentFragment,
options?: CreateRootOptions,
): RootType {
if (__DEV__) {

View File

@ -672,9 +672,8 @@ export function clearContainer(container: Container): void {
if (container.nodeType === ELEMENT_NODE) {
((container: any): Element).textContent = '';
} else if (container.nodeType === DOCUMENT_NODE) {
const body = ((container: any): Document).body;
if (body != null) {
body.textContent = '';
if (container.documentElement) {
container.removeChild(container.documentElement);
}
}
}

View File

@ -164,7 +164,7 @@ ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = funct
};
export function createRoot(
container: Element | DocumentFragment,
container: Element | Document | DocumentFragment,
options?: CreateRootOptions,
): RootType {
if (!isValidContainer(container)) {