Skip to content

Bug Report: rx.clipboard paste event handler not binding in rx.dialog when rendered dynamically #6032

Closed

Description

@TerraX3000

Bug Report: rx.clipboard paste event handler not binding in rx.dialog when rendered dynamically

Description

The rx.clipboard component's on_paste event handler does not fire on the first paste event when the component is inside an rx.dialog that is rendered dynamically (e.g., through rx.foreach or rx.match). The handler only starts working after the user types in the text area first.

Expected behavior: The on_paste handler should fire immediately on the first paste event, just like it does when the same dialog structure is rendered statically.

Actual behavior: The first paste bypasses the handler entirely (default browser paste behavior occurs for text). After typing any character in the text area, subsequent paste events are correctly caught by the handler.

Key finding: The issue specifically occurs when rx.clipboard is inside an rx.dialog that is rendered through dynamic patterns. The same clipboard component works fine when rendered statically, even inside a dialog.

Environment

  • Reflex version: 0.8.19
  • Python version: 3.12.7
  • OS: Linux

Minimal Reproducible Example

File: clipboard_bug_demo.py

import reflex as rx
from typing import List

class StaticClipboardState(rx.State):
    """State for the static component"""
    feedback: str = ""
    image_attachments: List[str] = []

    @rx.event
    def on_paste(self, data: list[tuple[str, str]]):
        print(f"[STATIC] on_paste called with {len(data)} items")
        for mime_type, item in data:
            print(f"[STATIC] Processing: {mime_type}")
            if mime_type.startswith("image/"):
                print(f"[STATIC] Image found, adding to attachments")
                self.image_attachments = self.image_attachments + [item]
                return
        
        print("[STATIC] No image found in paste data")
        return rx.toast.warning("STATIC: Only image attachments are allowed.")

    @rx.event
    def set_feedback(self, feedback: str):
        self.feedback = feedback

    @rx.event
    def remove_image(self, index: int):
        self.image_attachments.pop(index)


class DynamicClipboardState(rx.State):
    """State for the dynamic component"""
    feedback: str = ""
    image_attachments: List[str] = []
    component_type: str = "clipboard_test"

    @rx.event
    def on_paste(self, data: list[tuple[str, str]]):
        print(f"[DYNAMIC] on_paste called with {len(data)} items")
        for mime_type, item in data:
            print(f"[DYNAMIC] Processing: {mime_type}")
            if mime_type.startswith("image/"):
                print(f"[DYNAMIC] Image found, adding to attachments")
                self.image_attachments = self.image_attachments + [item]
                return
        
        print("[DYNAMIC] No image found in paste data")
        return rx.toast.warning("DYNAMIC: Only image attachments are allowed.")

    @rx.event
    def set_feedback(self, feedback: str):
        self.feedback = feedback

    @rx.event
    def remove_image(self, index: int):
        self.image_attachments.pop(index)


def static_clipboard_component() -> rx.Component:
    """This version WORKS correctly - paste fires immediately even in dialog"""
    return rx.box(
        rx.heading("Static Component in Dialog (WORKS)", size="5"),
        rx.text("Click button to open dialog, then paste an image", margin_y="8px"),
        rx.dialog.root(
            rx.dialog.trigger(
                rx.button(
                    "Open Dialog to Test",
                    size="3",
                    variant="surface",
                    color_scheme="green",
                ),
            ),
            rx.dialog.content(
                rx.dialog.title("Static Clipboard in Dialog"),
                rx.flex(
                    rx.text("Paste an image here - works on first paste", margin_y="8px"),
                    rx.clipboard(
                        rx.text_area(
                            value=StaticClipboardState.feedback,
                            rows="10",
                            on_change=StaticClipboardState.set_feedback,
                            placeholder="Paste an image here...",
                        ),
                        on_paste=StaticClipboardState.on_paste.prevent_default,
                    ),
                    rx.hstack(
                        rx.foreach(
                            StaticClipboardState.image_attachments,
                            lambda image, index: rx.flex(
                                rx.image(src=image, height="50px", width="50px"),
                                rx.icon("x", on_click=StaticClipboardState.remove_image(index))
                            )
                        ),
                    ),
                    rx.dialog.close(
                        rx.button("Close", margin_top="8px"),
                    ),
                    direction="column",
                    spacing="3",
                ),
                max_width="500px",
            ),
        ),
        padding="20px",
        border="2px solid green",
    )


def dynamic_clipboard_component() -> rx.Component:
    """This version FAILS - paste doesn't work until after typing when inside a dialog"""
    return rx.box(
        rx.heading("Dynamic Component in Dialog (BROKEN)", size="5"),
        rx.text("Click button to open dialog, then paste an image", margin_y="8px"),
        rx.dialog.root(
            rx.dialog.trigger(
                rx.button(
                    "Open Dialog to Test",
                    size="3",
                    variant="surface",
                    color_scheme="red",
                ),
            ),
            rx.dialog.content(
                rx.dialog.title("Dynamic Clipboard in Dialog"),
                rx.flex(
                    rx.text("Paste an image here - REQUIRES typing first", margin_y="8px"),
                    rx.clipboard(
                        rx.text_area(
                            value=DynamicClipboardState.feedback,
                            rows="10",
                            on_change=DynamicClipboardState.set_feedback,
                            placeholder="Paste an image here...",
                        ),
                        on_paste=DynamicClipboardState.on_paste.prevent_default,
                    ),
                    rx.hstack(
                        rx.foreach(
                            DynamicClipboardState.image_attachments,
                            lambda image, index: rx.flex(
                                rx.image(src=image, height="50px", width="50px"),
                                rx.icon("x", on_click=DynamicClipboardState.remove_image(index))
                            )
                        ),
                    ),
                    rx.dialog.close(
                        rx.button("Close", margin_top="8px"),
                    ),
                    direction="column",
                    spacing="3",
                ),
                max_width="500px",
            ),
        ),
        padding="20px",
        border="2px solid red",
    )


def render_component(component_type: str):
    """Simulates dynamic component rendering"""
    return rx.match(
        component_type,
        ("clipboard_test", dynamic_clipboard_component()),
        rx.fragment(),
    )


def index() -> rx.Component:
    return rx.container(
        rx.vstack(
            rx.heading("rx.clipboard Bug Demonstration", size="7"),
            rx.text("Test by opening each dialog and pasting an image. Check console for [STATIC] vs [DYNAMIC] logs.", margin_bottom="20px"),
            
            # Static version - WORKS
            static_clipboard_component(),
            
            rx.divider(margin_y="20px"),
            
            # Dynamic version - BROKEN
            # This simulates rendering through rx.foreach or rx.match
            rx.foreach(
                [DynamicClipboardState.component_type],
                lambda comp_type: render_component(comp_type)
            ),
            
            spacing="4",
            padding="20px",
        ),
        max_width="800px",
    )


app = rx.App()
app.add_page(index)

Steps to Reproduce

  1. Save the code above as clipboard_bug_demo.py
  2. Run reflex init (if needed) and reflex run
  3. Open the app in a browser
  4. Copy an image to your clipboard (screenshot, image file, etc.)

Test the STATIC component (green border):

  1. Click the green "Open Dialog to Test" button
  2. In the opened dialog, click in the text area
  3. Paste (Ctrl+V or Cmd+V)
  4. ✅ Result: The image appears immediately, console shows "[STATIC] on_paste called"

Test the DYNAMIC component (red border):

  1. Refresh the page to reset state
  2. Click the red "Open Dialog to Test" button
  3. In the opened dialog, click in the text area
  4. Paste (Ctrl+V or Cmd+V)
  5. ❌ Result: Image paste does nothing. Console shows NO "[DYNAMIC] on_paste called" message
  6. Type any character in the text area
  7. Paste again
  8. ✅ Result: NOW the image appears and console shows "[DYNAMIC] on_paste called"

Root Cause Analysis

The rx.clipboard component's paste event listener is not being properly attached when:

  1. The component is inside an rx.dialog
  2. AND the dialog is rendered through dynamic rendering patterns (rx.foreach, rx.match, etc.)

The event handler only binds after the first user interaction with the text area (typing). The same dialog structure works perfectly when rendered statically, indicating this is an issue with how event handlers are bound in dynamically rendered dialog content.

Workarounds Attempted

None of these worked:

  • Adding on_mount handler to text area
  • Adding on_focus handler to text area
  • Using a key prop that changes to force remount
  • Wrapping in additional boxes with mount handlers
  • Using controlled dialog state
  • Explicitly initializing state before render
  • Conditional rendering based on initialization flag

Impact

This prevents building reusable clipboard-enabled dialog components that can be dynamically rendered, which is a common pattern for CMS-driven or configurable UIs. Workarounds like requiring users to type before pasting create a poor user experience.

Expected Fix

The rx.clipboard component should properly bind its event handlers when inside rx.dialog components that are rendered dynamically, ensuring the on_paste handler fires on the very first paste event just like it does in statically rendered dialogs.

Image Image

Activity

  1. debangshu919 commented on Dec 11, 2025

    @debangshu919
    Contributor

    i would like to work on this issue.

  2. masenf commented on Dec 11, 2025

    @masenf
    Collaborator

    @debangshu919 thank you

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