Reactive user interfaces with pure Python
—
Core functionality for defining ReactPy components with proper lifecycle management and rendering. Components are the fundamental building blocks of ReactPy applications, created using the @component decorator.
The @component decorator transforms a regular Python function into a ReactPy component that can manage state and participate in the rendering lifecycle.
@component
def component_function(*args, key: Any | None = None, **kwargs) -> ComponentType | VdomDict | str | None: ...Parameters:
function: The component's render function that returns VDOM, string, or Nonekey: Optional key for component identity in lists (passed as keyword argument)Returns: A constructor function that creates Component instances
Usage Examples:
from reactpy import component, html
@component
def HelloWorld(name: str = "World"):
return html.h1(f"Hello, {name}!")
@component
def Button(text: str, on_click=None):
return html.button({"onClick": on_click}, text)
# Usage with key for lists
items = ["Apple", "Banana", "Cherry"]
fruit_buttons = [
Button(item, key=item)
for item in items
]The Component class represents an instantiated component with rendering capabilities and metadata.
class Component:
key: Any | None
type: Callable[..., ComponentType | VdomDict | str | None]
def __init__(
self,
function: Callable[..., ComponentType | VdomDict | str | None],
key: Any | None,
args: tuple[Any, ...],
kwargs: dict[str, Any],
sig: inspect.Signature,
) -> None: ...
def render(self) -> ComponentType | VdomDict | str | None: ...Attributes:
key: Component key for identity tracking in liststype: The original component functionMethods:
render(): Execute the component function with its arguments to produce VDOMFunctional Components:
@component
def Counter():
count, set_count = use_state(0)
return html.div(
html.p(f"Count: {count}"),
html.button({"onClick": lambda: set_count(count + 1)}, "Increment")
)Components with Props:
@component
def UserCard(name: str, email: str, avatar_url: str = None):
return html.div(
html.img({"src": avatar_url}) if avatar_url else None,
html.h3(name),
html.p(email)
)Components with Children:
@component
def Card(*children, title: str = None):
return html.div(
{"className": "card"},
html.h2(title) if title else None,
html.div({"className": "card-body"}, *children)
)Conditional Rendering:
@component
def ConditionalComponent(show_content: bool = True):
if not show_content:
return html.p("No content to display")
return html.div(
html.h1("Content"),
html.p("This is the main content")
)Components may raise TypeError if using reserved parameter names:
# This will raise TypeError
@component
def invalid_component(key: str): # 'key' is reserved
return html.div(key)The key parameter is reserved for component identity and cannot be used as a regular parameter in component functions.
Install with Tessl CLI
npx tessl i tessl/pypi-reactpy