Skip to content

Client-side component events break input focus #1195

Closed
@Archmonger

Description

@Archmonger

Discussed in #1187

Originally posted by williamneto January 13, 2024
So, while developing reactpy-material i faced a problem that might be related to the reactpy architecture for custom components.

To showcase the problem i created this small component, just a normal textfield. The problem is when attaching a on_change event to this custom component, the event on the page doesn't behavior as expected. Each time you type in the field (and trigger the onChange event) the page focus is moved out of the input element.

So, a simple custom TextField like that

import React from "react";
import ReactDOM from "react-dom";
import htm from "htm";

const html = htm.bind(React.createElement);

export function bind(node, config) {
  return {
    create: (type, props, children) => React.createElement(type, props, ...children),
    render: (element) => ReactDOM.render(element, node),
    unmount: () => ReactDOM.unmountComponentAtNode(node),
  }
}

export function TextField(attrs) {
  return html`
    <div>
      <input type="text" ...${attrs}>
    </div>`;
}
from pathlib import Path
from typing import Any
from reactpy.web.module import export, module_from_file
from reactpy import component

_js_module = module_from_file(
    "reactpy-events-problem",
    file=Path(__file__).parents[0] / "bundle.js"
)

new_text_field = export(_js_module, "TextField")

@component
def text_field(attrs: Any ={}):
    return new_text_field(attrs)

And when you try to use it like that

from reactpy import component, run, html, use_state
from reactpy_events_problem import text_field

@component
def app():
    text, set_text = use_state("Text")

    return html.div(
        html.h1(text),
        text_field(
            attrs={
                "value": text,
                "onChange": lambda e: set_text(e["target"]["value"])
            }
        )
    )

run(app)

You end up with this weird behavior at the page focus, making type in this field very unpratical

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions