pysxLearn by building

Compose an interface · Lesson 11 of 28

Components, props and children

Compose reusable typed callables without sharing private instance state.

A component is a Python callable that returns content. Props describe the inputs it accepts; children provide caller-owned content to place inside its layout. Components let one clear interface hide markup details.

Import components normally and use their PascalCase names in markup. The scoped compiler records lexical references, including names used only as tags. Keep the application loader installed before importing template-producing modules.

Understand the moving parts

The shared card below accepts a heading and arbitrary children. Two instances each own a count; changing the shared heading updates their presentation without turning the counts into one shared variable.

A styled callable can extend a component's appearance while preserving its content and prop contract. Children retain the caller's namespace: a component does not gain permission to reinterpret a caller's dynamic source.

Walk through the code

from pysx import Children, Fragment, local_state, pysx, signal


def app() -> Fragment:
    title = signal("Shared heading")

    def Card(*, number: int, children: Children | None = None) -> Fragment:
        count = local_state("count", 0)

        def increment(_: object) -> None:
            count.update(lambda value: value + 1)

        return pysx(t"""
            section(data-instance={number})
                h3: {title}
                {children}
                button(data-card-increment={number} onClick={increment}):
                    "Increment instance"
                output(data-card-count={number}): {count}
        """)

    return pysx(t"""
        label(for="component-title"): "Heading shared by both component instances"
        input(id="component-title" bindValue={title})
        Card(number={1}): "Caller-owned content for the first card."
        Card(number={2}): "Different children, independent local state."
    """)

Both Card instances read the same heading signal and receive different caller-owned children. Their keyed local count belongs to each component instance, so incrementing the first leaves the second unchanged.

Try it live

Change the common heading and increment only the first component instance.

What to observe

Both headings change, but only the first instance's local count increments.

Shared heading

Caller-owned content for the first card.0

Shared heading

Different children, independent local state.0

Take this with you

Share component definitions, not accidental instance state.