Skip to content
Source
Sign inSign up
TanStack/redact

Events inside a portal don't bubble to the portal's React parents #119

Send to my agent
OpenEduKegler(GitHub profile, opens in a new tab) opened this issue 2 comments

In React DOM, an event fired inside a portal bubbles through the React tree, so the component that renders the portal receives it. In Redact the event bubbles only through the DOM tree, so no React parent of the portal sees it.

Reproduction

Both links open the same StackBlitz project, so you install nothing. They differ only in the start script:

RedactReact DOM
Both cases fail on RedactBoth cases pass on React DOM

The smallest case is one parent with one portal:

import { useState } from 'react'
import { createPortal } from 'react-dom'

function App() {
	const [clicks, setClicks] = useState(0)
	return (
		<div onClick={() => setClicks((n) => n + 1)}>
			<p>Parent saw {clicks} clicks</p>
			{createPortal(<button>Inside portal</button>, document.body)}
		</div>
	)
}

Expected. Each click on Inside portal reaches the parent, as it does in React DOM.

Actual. In Redact the parent sees 0 clicks.

I get the same result in Chromium and WebKit, with real Playwright clicks on production builds and by hand on the StackBlitz links.

Impact on headless UI libraries

Libraries decide whether a click lands inside or outside a layer through events that cross the portal. Without React-tree bubbling, a layer nested in a portal counts its own clicks as outside:

  • Radix. Clicking an item of a Popover inside a Dialog closes the Dialog. DismissableLayer marks a pointer press as inside through its onPointerDownCapture, and the popover content reaches that handler only through the React tree. The StackBlitz project shows this case with radix-ui 1.8.1.
  • Base UI. #70 looks like the same cause. A submenu in a portal closes on outside-press before its link gets the click.

Cause

In 0.2.3, createPortal only returns the element, and synthetic-event.js wraps the native event. Each handler listens on its own element, so the event follows the DOM tree. The compatibility docs list portals as supported, and SURFACE.md marks createPortal as basic. Neither page mentions that portal events follow the DOM tree.

Do you want Redact to match React here? If you do, I can send a PR once you pick the approach. If you don't, a line in the compatibility docs that says portal events follow the DOM tree would tell users what to expect.

Versions. Redact 0.2.3, radix-ui 1.8.1, React 19.2.0, Vite 8.3.5, @vitejs/plugin-react 6.1.2, Chromium 156.0.8078.4, and WebKit 27.2 from Playwright.

  1. Another case with the same cause, without a portal: invalid doesn’t bubble in the DOM, so an onInvalid on an ancestor never runs in Redact. React DOM delivers it to every React ancestor. MUI’s TextField passes onInvalid to its wrapper <div>, so custom validation messages set there are lost.

    const App = () => {
      const [invalid, setInvalid] = useState(0)
    
      return (
        <form>
          <div onInvalid={() => setInvalid((n) => n + 1)}>
            <input required aria-label="Name" />
          </div>
          <button>Submit</button>
          <p>Invalid events: {invalid}</p>
        </form>
      )
    }

    Clicking “Submit” shows “Invalid events: 1” on React DOM 19.2.7 and “Invalid events: 0” on Redact 0.2.3.

  2. Confirmed the nested Radix Dialog/Popover case on Redact 0.2.4, with a standalone cmdk selection reproduction.

    Expected: selecting “Example” updates the popover trigger and closes only the popover; the parent dialog remains open. React 19.3.1 does this.

    Actual: the parent dialog disappears on Redact 0.2.4. The assertion below fails with 0 !== 1. The identical production SSR/hydration fixture passes on React. This reproduces the reported symptom; I have not independently proved its internal cause.

    Tested with Bun 1.4.4, Chromium 151.0.7922.173 on Linux, Playwright 1.64.1, Vite 8.3.5, radix-ui 1.8.1 and cmdk 1.1.1. All direct dependency versions are pinned below. React Compiler is enabled in both runs. The build also asserts that the Redact module graph contains no upstream React/React DOM runtime.

    Create an empty directory with these five files, then run:

    bun install
    bunx playwright install chromium
    bun run check:react   # PASS
    bun run check:redact  # FAIL: Selecting a portaled option must keep the dialog open

    An already installed Chromium can be selected instead:

    PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium bun run check:react
    PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium bun run check:redact

    The observed results above used that installed-browser override. The driver uses actual Playwright pointer clicks and builds both the server and browser bundles before testing.

    Complete runnable reproduction

    package.json

    {
    	"private": true,
    	"type": "module",
    	"scripts": {
    		"check:react": "bun --no-env-file check.ts",
    		"check:redact": "USE_REDACT=1 bun --no-env-file check.ts"
    	},
    	"dependencies": {
    		"@rolldown/plugin-babel": "0.2.4",
    		"@tanstack/redact": "0.2.4",
    		"@vitejs/plugin-react": "6.1.2",
    		"babel-plugin-react-compiler": "1.0.0",
    		"@babel/core": "8.0.7",
    		"playwright": "1.64.1",
    		"vite": "8.3.5",
    		"react": "19.3.1",
    		"react-dom": "19.3.1",
    		"radix-ui": "1.8.1",
    		"cmdk": "1.1.1"
    	}
    }

    App.tsx

    import { useState } from "react";
    import { Dialog, Popover } from "radix-ui";
    import { Command } from "cmdk";
    export function App({ name }: { name: string }) {
    	const [open, setOpen] = useState(false);
    	const [value, setValue] = useState("None");
    	return (
    		<main>
    			<p>{name}</p>
    			<Dialog.Root>
    				<Dialog.Trigger>Open dialog</Dialog.Trigger>
    				<Dialog.Portal>
    					<Dialog.Overlay />
    					<Dialog.Content>
    						<Dialog.Title>Runtime dialog</Dialog.Title>
    						<Dialog.Description>
    							Selection must keep dialog open
    						</Dialog.Description>
    						<Popover.Root open={open} onOpenChange={setOpen}>
    							<Popover.Trigger aria-label="Choose item">
    								{value}
    							</Popover.Trigger>
    							<Popover.Portal>
    								<Popover.Content>
    									<Command>
    										<Command.Input />
    										<Command.List>
    											<Command.Item
    												onSelect={() => {
    													setValue("Example");
    													setOpen(false);
    												}}
    											>
    												Example
    											</Command.Item>
    										</Command.List>
    									</Command>
    								</Popover.Content>
    							</Popover.Portal>
    						</Popover.Root>
    					</Dialog.Content>
    				</Dialog.Portal>
    			</Dialog.Root>
    		</main>
    	);
    }

    client.tsx

    import { hydrateRoot } from "react-dom/client";
    import { App } from "./App";
    
    const root = document.getElementById("root");
    if (!root) throw new Error("Missing runtime fixture root");
    hydrateRoot(root, <App name="Permitted customer name" />);

    server.tsx

    import { renderToString } from "react-dom/server";
    import { App } from "./App";
    export function render() {
    	return renderToString(<App name="Permitted customer name" />);
    }

    check.ts

    import assert from "node:assert/strict";
    import { mkdtemp, rm } from "node:fs/promises";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import babel from "@rolldown/plugin-babel";
    import { redact } from "@tanstack/redact/vite";
    import react, { reactCompilerPreset } from "@vitejs/plugin-react";
    import { chromium } from "playwright";
    import { build, type InlineConfig } from "vite";
    
    // This uses production Vite builds, not Bun's unaliased React test runtime.
    const root = import.meta.dirname;
    const useRedact = process.env.USE_REDACT === "1";
    const output = await mkdtemp(join(tmpdir(), "redact-repro-"));
    const config = (): InlineConfig => ({
    	configFile: false,
    	root,
    	logLevel: "warn",
    	ssr: { noExternal: true },
    	plugins: [
    		react(),
    		useRedact ? redact() : [],
    		babel({ presets: [reactCompilerPreset()] }),
    		{
    			name: "verify-single-runtime",
    			generateBundle() {
    				if (!useRedact) return;
    				const modules = [...this.getModuleIds()];
    				assert.ok(modules.some((id) => id.includes("/@tanstack/redact/")));
    				assert.deepEqual(
    					modules.filter((id) =>
    						/\/node_modules\/(react|react-dom)\//.test(id),
    					),
    					[],
    				);
    			},
    		},
    	],
    });
    let server: ReturnType<typeof Bun.serve> | undefined;
    let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined;
    try {
    	await build({
    		...config(),
    		build: {
    			outDir: join(output, "client"),
    			emptyOutDir: true,
    			rollupOptions: {
    				input: join(root, "client.tsx"),
    				output: { entryFileNames: "entry.js" },
    			},
    		},
    	});
    	await build({
    		...config(),
    		build: {
    			ssr: join(root, "server.tsx"),
    			outDir: join(output, "server"),
    			emptyOutDir: true,
    		},
    	});
    	const { render } = await import(join(output, "server/server.js"));
    	const html = `<!doctype html><html lang="en"><body><div id="root">${render()}</div><script type="module" src="/entry.js"></script></body></html>`;
    	server = Bun.serve({
    		hostname: "127.0.0.1",
    		port: 0,
    		fetch(request) {
    			const path = new URL(request.url).pathname;
    			if (path === "/favicon.ico") return new Response(null, { status: 204 });
    			if (path === "/")
    				return new Response(html, { headers: { "content-type": "text/html" } });
    			return new Response(Bun.file(join(output, "client", path)));
    		},
    	});
    	browser = await chromium.launch({
    		executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
    	});
    	const page = await browser.newPage();
    	page.setDefaultTimeout(8000);
    	const errors: string[] = [];
    	page.on("pageerror", (error) => errors.push(error.message));
    	page.on("console", (message) => {
    		if (message.type() === "error") errors.push(message.text());
    	});
    	await page.goto(server.url.href);
    	await page.waitForLoadState("networkidle");
    	assert.deepEqual(errors, []);
    	await page.getByRole("button", { name: "Open dialog" }).click();
    	const dialog = page.getByRole("dialog");
    	await dialog.waitFor();
    	await page.getByRole("button", { name: "Choose item" }).click();
    	await page.getByRole("option", { name: "Example", exact: true }).click();
    	await page.waitForTimeout(250);
    	assert.equal(
    		await dialog.count(),
    		1,
    		"Selecting a portaled option must keep the dialog open",
    	);
    	assert.equal(
    		await page.getByRole("button", { name: "Choose item" }).textContent(),
    		"Example",
    	);
    	assert.deepEqual(errors, []);
    	console.log(`PASS ${useRedact ? "Redact" : "React"} nested portal selection`);
    } finally {
    	await browser?.close();
    	server?.stop(true);
    	await rm(output, { recursive: true, force: true });
    }

Sign in to join this conversation.