Skip to content

Commit

Permalink
Consider Text node in the root hydration
Browse files Browse the repository at this point in the history
  • Loading branch information
HenriqueLimas committed Sep 29, 2024
1 parent db24098 commit 7776122
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,10 @@ export function canHydrateInstance(
props: Props,
inRootOrSingleton: boolean,
): null | Instance {
while (instance.nodeType === ELEMENT_NODE) {
while (
instance.nodeType === ELEMENT_NODE ||
(inRootOrSingleton && instance.nodeType === TEXT_NODE)
) {
const element: Element = (instance: any);
const anyProps = (props: any);
if (element.nodeName.toLowerCase() !== type.toLowerCase()) {
Expand Down Expand Up @@ -1177,11 +1180,9 @@ export function canHydrateInstance(
}
instance = nextInstance;
}
// This is a suspense boundary or Text node or we got the end.
// This is a suspense boundary or we got the end.
// Suspense Boundaries are never expected to be injected by 3rd parties. If we see one it should be matched
// and this is a hydration error.
// Text Nodes are also not expected to be injected by 3rd parties. This is less of a guarantee for <body>
// but it seems reasonable and conservative to reject this as a hydration error as well
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -788,4 +788,20 @@ describe('ReactDOMServerHydration', () => {

expect(ref.current).toBe(button);
});

it('ignores text nodes on root when hydrating', async () => {
const root = document.createElement('div');

root.innerHTML = '<button>Click</button>';
const button = root.firstChild;

const emptyText = document.createTextNode('');
root.insertBefore(emptyText, button);

const ref = React.createRef();
await act(() => {
ReactDOMClient.hydrateRoot(root, <button ref={ref}>Click</button>);
});
expect(ref.current).toBe(button);
});
});

0 comments on commit 7776122

Please sign in to comment.