Repository navigation
Description
Summary
In React Native's Fabric renderer (ReactFiberConfigFabric.js), mounting a <Fragment ref={...}> that contains a direct raw text (HostText) child inside <Text> crashes on initial mount — despite #35637 guarding the dynamic-insertion path (commitNewChildToFragmentInstance) — throwing:
Error: Expected to find a host node. This is a bug in React.
By code inspection, the same unguarded getPublicInstanceFromHostFiber lookup is also reached from FragmentInstance operations (observeUsing, unobserveUsing, getClientRects, and compareDocumentPosition) whenever a fragment contains a HostText child.
Related
- Related: PR
#35630(Add text node support to FragmentInstance operations, stacked fixtures in#35631) added DOM text-node support and explicitly deferred Fabric support. - Related: PR
#35637(Notify FragmentInstance of added/removed text) added an early return for text nodes (if (childInstance.canonical == null) return;) incommitNewChildToFragmentInstance, but the initial-mount path (createFragmentInstance) and the otherFragmentInstancetraversal operations were not updated to handleHostText.
Affected version
- Published
[email protected](Libraries/Renderer/implementations/ReactFabric-dev.js) with[email protected](Node.jsv22.22.2, mockedfabricUIManager) - Verified unchanged on
mainatedae846a9a17442c00429f2b15375afbfa0376c9
Reproduction
In an empty directory (no React monorepo checkout needed):
npm install [email protected] [email protected]
node <<'JS'
const Module = require('module');
const origLoad = Module._load;
const viewConfigs = {
RCTView: {uiViewClassName: 'RCTView', validAttributes: {}},
RCTText: {uiViewClassName: 'RCTText', validAttributes: {}},
};
const roots = new Map();
const fabricUIManager = {
createNode: (tag, viewName, rootTag, props, handle) => ({tag, viewName, props, children: [], handle}),
cloneNode: n => ({...n, children: [...n.children]}),
cloneNodeWithNewChildren: n => ({...n, children: []}),
cloneNodeWithNewProps: (n, p) => ({...n, props: p}),
cloneNodeWithNewChildrenAndProps: (n, p) => ({...n, props: p, children: []}),
createChildSet: () => [],
appendChild: (parent, child) => { parent.children.push(child); },
appendChildToSet: (set, child) => { set.push(child); },
completeRoot: (rootTag, childSet) => { roots.set(rootTag, childSet); },
};
const privateInterface = {
RawEventEmitter: {emit() {}},
ReactFiberErrorDialog: {showErrorDialog: () => true},
ReactNativeFeatureFlags: {},
ReactNativeViewConfigRegistry: {get: name => viewConfigs[name]},
createAttributePayload: props => props,
diffAttributePayloads: (a, b) => b,
createPublicInstance: (tag, viewConfig, handle) => ({__tag: tag, __viewName: viewConfig.uiViewClassName, __handle: handle}),
createPublicRootInstance: rootTag => ({__rootTag: rootTag}),
createPublicTextInstance: handle => ({__text: true, __handle: handle}),
deepFreezeAndThrowOnMutationInDev: () => {},
dispatchNativeEvent: () => {},
fabricUIManager,
getInternalInstanceHandleFromPublicInstance: inst => inst.__handle,
getNativeTagFromPublicInstance: inst => inst.__tag,
getNodeFromPublicInstance: inst => inst,
};
Module._load = function (request) {
if (request === 'react-native/setup-env') return {};
if (request === 'react-native/react-private-interface') return privateInterface;
return origLoad.apply(this, arguments);
};
global.__DEV__ = true;
global.IS_REACT_ACT_ENVIRONMENT = true;
const React = require('react');
const ReactFabric = require('react-native/Libraries/Renderer/implementations/ReactFabric-dev.js');
async function testCase(label, rootTag, element) {
let err;
try {
await React.act(() => {
ReactFabric.render(element, rootTag, null, true);
});
} catch (e) {
err = e;
}
const tree = roots.get(rootTag);
console.log(
label,
'=>',
err
? `${err.name}: ${err.message}`
: `OK (root children: ${tree.map(c => `${c.viewName}[${c.children.map(x => x.viewName).join(',')}]`).join(',')})`,
);
if (err) {
console.log(' ' + err.stack.split('\n').slice(1, 5).map(s => s.trim()).join('\n '));
}
}
(async () => {
const refElem = React.createRef();
const refText = React.createRef();
await testCase(
'Control 1 (plain raw text in Text): ',
11,
React.createElement('RCTText', null, 'hello'),
);
await testCase(
'Control 2 (Fragment ref wrapping Text):',
21,
React.createElement(
'RCTView',
null,
React.createElement(React.Fragment, {ref: refElem}, React.createElement('RCTText', null, 'hello')),
),
);
console.log(' Control 2 ref.current attached:', refElem.current !== null);
await testCase(
'Bug (Fragment ref wrapping raw text): ',
31,
React.createElement('RCTText', null, React.createElement(React.Fragment, {ref: refText}, 'hello')),
);
})();
JSActual output
Control 1 (plain raw text in Text): => OK (root children: RCTText[RCTRawText])
Control 2 (Fragment ref wrapping Text): => OK (root children: RCTView[RCTText])
Control 2 ref.current attached: true
Bug (Fragment ref wrapping raw text): => Error: Expected to find a host node. This is a bug in React.
at getPublicInstanceFromHostFiber (.../react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:17220:15)
at addFragmentHandleToFiber (.../react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:17300:15)
at traverseVisibleInstancesAndTextInstances (.../react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:1843:13)
at commitAttachRef (.../react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:11236:15)
Expected behavior
Mounting <RCTText><Fragment ref={refText}>hello</Fragment></RCTText> should succeed without throwing, attaching refText.current cleanly (consistent with Control 1 and Control 2, and with the insertion-path handling already added in #35637).
Root cause
- In
ReactFiberConfigFabric.js,createFragmentInstancecallstraverseFragmentInstancesAndTextInstances(fragmentFiber, addFragmentHandleToFiber, fragmentInstance)(#L882) — a thin wrapper inReactFiberTreeReflection.js#L349-L363that delegates directly totraverseVisibleInstancesAndTextInstances(inlined in the compiledReactFabric-dev.jsbundle above) and visitsHostTextfibers as well asHostComponentfibers. addFragmentHandleToFibercallsgetPublicInstanceFromHostFiber(child)(#L859).- Because a Fabric
TextInstancehas no.canonicalproperty,getPublicInstance(fiber.stateNode)returnsnull, andgetPublicInstanceFromHostFiberthrows'Expected to find a host node. This is a bug in React.'at#L355. - By contrast,
commitNewChildToFragmentInstancealready guardsif (childInstance.canonical == null) return;at#L902. - By inspection, the same unguarded
getPublicInstanceFromHostFibercall ontraverseFragmentInstancesAndTextInstanceschildren also exists inobserveChild(#L712),unobserveChild(#L741),compareDocumentPosition(#L774-L777), andcollectClientRects(#L843).
Suggested fix
Decide the text-node handling consistently across the shared Fabric FragmentInstance helpers:
- For element-only bookkeeping and observation (
createFragmentInstance/addFragmentHandleToFiber,observeUsing,unobserveUsing), skipHostTextfibers (matching the existingcanonical == nullearly return incommitNewChildToFragmentInstanceat#L902or traversing host elements only). - For geometry/position queries (
getClientRects,compareDocumentPosition), resolveHostTextviagetPublicTextInstance(orgetPublicInstanceFromHostFibermade text-aware where appropriate) or delegate to the parentRCTTexthost instance, matching the Fabric follow-up noted in#35630.
Adding a regression test in packages/react-native-renderer/src/__tests__/ReactFabricFragmentRefs-test.internal.js mounting <Text><Fragment ref={fragmentRef}>hello</Fragment></Text> and asserting expect(fragmentRef.current).not.toBe(null) will prevent regressions.
Activity