Skip to content

[react-native-renderer] Fabric FragmentInstance throws when mounting or operating on a Fragment with direct HostText children #38440

Backlog

Description

@Tortleya

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;) in commitNewChildToFragmentInstance, but the initial-mount path (createFragmentInstance) and the other FragmentInstance traversal operations were not updated to handle HostText.

Affected version

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')),
  );
})();
JS

Actual 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

  1. In ReactFiberConfigFabric.js, createFragmentInstance calls traverseFragmentInstancesAndTextInstances(fragmentFiber, addFragmentHandleToFiber, fragmentInstance) (#L882) — a thin wrapper in ReactFiberTreeReflection.js#L349-L363 that delegates directly to traverseVisibleInstancesAndTextInstances (inlined in the compiled ReactFabric-dev.js bundle above) and visits HostText fibers as well as HostComponent fibers.
  2. addFragmentHandleToFiber calls getPublicInstanceFromHostFiber(child) (#L859).
  3. Because a Fabric TextInstance has no .canonical property, getPublicInstance(fiber.stateNode) returns null, and getPublicInstanceFromHostFiber throws 'Expected to find a host node. This is a bug in React.' at #L355.
  4. By contrast, commitNewChildToFragmentInstance already guards if (childInstance.canonical == null) return; at #L902.
  5. By inspection, the same unguarded getPublicInstanceFromHostFiber call on traverseFragmentInstancesAndTextInstances children also exists in observeChild (#L712), unobserveChild (#L741), compareDocumentPosition (#L774-L777), and collectClientRects (#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), skip HostText fibers (matching the existing canonical == null early return in commitNewChildToFragmentInstance at #L902 or traversing host elements only).
  • For geometry/position queries (getClientRects, compareDocumentPosition), resolve HostText via getPublicTextInstance (or getPublicInstanceFromHostFiber made text-aware where appropriate) or delegate to the parent RCTText host 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions