Claude Skill

live-component

Symfony UX LiveComponent: live search, live filters, dependent selects and form validation as users type. Use for reactive PHP and Twig components, #[AsLiveComponent], LiveProp, LiveAction, data-model, loading states, emit/listen, lazy rendering and LiveResponse downloads.

LLM Mart · 0 points · 0 views 1 listing impressions 0 install-command copies
Download smnandre-symfony-ux-skills-skills_live-component-78c25ed.zip · 18 KB

Install

skills CLI npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/live-component
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
Git git clone https://github.com/smnandre/symfony-ux-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

LiveComponent

TwigComponents that re-render dynamically via AJAX. Build reactive UIs in PHP + Twig with zero JavaScript. Every user interaction triggers a server round-trip that re-renders the component and morphs the DOM.

When to Use LiveComponent

Use LiveComponent when a component's output depends on user interaction: search results that update as you type, forms with real-time validation, filters that refine a list, anything where the UI needs to change based on user input and that change requires server-side data or logic.

If the component never re-renders after initial load, use TwigComponent instead (lighter, rendered once). If the interaction is purely client-side (toggle, animation), use Stimulus instead.

Installation

composer require symfony/ux-live-component

Quick Reference

#[AsLiveComponent]           Make component live (re-renderable via AJAX)
#[LiveProp]                  State that persists across re-renders
#[LiveProp(writable: true)]  State that the frontend can modify
#[LiveAction]                Server method callable from frontend
data-model="prop"            Two-way bind input to LiveProp
data-action="live#action"    Call LiveAction on event
data-loading="..."           Show/hide/style elements during AJAX
{{ attributes }}             REQUIRED on root element (wires the Stimulus controller)

Basic Example

// src/Twig/Components/Counter.php
namespace App\Twig\Components;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class Counter
{
    use DefaultActionTrait;

    #[LiveProp]
    public int $count = 0;

    #[LiveAction]
    public function increment(): void
    {
        $this->count++;
    }

    #[LiveAction]
    public function decrement(): void
    {
        $this->count--;
    }
}
{# templates/components/Counter.html.twig #}
<div {{ attributes }}>
    <button data-action="live#action" data-live-action-param="decrement">-</button>
    <span>{{ count }}</span>
    <button data-action="live#action" data-live-action-param="increment">+</button>
</div>

Critical: The root element must render {{ attributes }}. This injects the Stimulus data-controller="live" attribute that makes the whole system work: every re-render depends on it.

LiveProp

State that persists between AJAX re-renders. Props are serialized to the frontend and sent back on every request.

Basic Props

#[LiveProp]
public string $query = '';

#[LiveProp]
public int $page = 1;

#[LiveProp]
public ?User $user = null;  // Entities auto-hydrate by ID

Writable Props (Two-way Binding)

Only writable props can be modified from the frontend via data-model:

#[LiveProp(writable: true)]
public string $search = '';

// Writable with specific fields for objects
#[LiveProp(writable: ['email', 'name'])]
public User $user;

URL Binding

Sync a prop to a URL query parameter: enables bookmarkable/shareable state:

#[LiveProp(writable: true, url: true)]
public string $query = '';
// URL becomes: ?query=search+term

// Custom parameter name
use Symfony\UX\LiveComponent\Metadata\UrlMapping;

#[LiveProp(writable: true, url: new UrlMapping(as: 'q'))]
public string $query = '';
// URL becomes: ?q=search+term

Hydration

Doctrine entities auto-hydrate by ID. For custom types:

#[LiveProp(hydrateWith: 'hydrateStatus', dehydrateWith: 'dehydrateStatus')]
public Status $status;

public function hydrateStatus(string $value): Status
{
    return Status::from($value);
}

public function dehydrateStatus(Status $status): string
{
    return $status->value;
}

Data Binding (data-model)

Bind inputs to writable LiveProps. When the input changes, the component re-renders with the new value. For a filter bound to the URL, see the live search example.

{# Re-render as the user types (default, debounced) #}
<input type="text" data-model="search">

{# Custom debounce -- wait 300ms after last keystroke #}
<input type="text" data-model="debounce(300)|search">

{# Only update on the "change" event (blur or Enter for text inputs) #}
<input type="text" data-model="on(change)|search">

{# Update model but don't re-render yet #}
<input type="text" data-model="norender|search">

{# Checkbox, radio, select #}
<input type="checkbox" data-model="enabled">
<select data-model="category">
    <option value="1">Category 1</option>
</select>

Validation Modifiers

{# Only update the model when input meets criteria #}
<input data-model="min_length(3)|search">
<input data-model="max_length(100)|bio">
<input type="number" data-model="min_value(0)|quantity">
<input type="number" data-model="max_value(999)|price">

LiveAction

Server methods callable from the frontend:

#[LiveAction]
public function save(): void
{
    // Called via data-action="live#action" data-live-action-param="save"
}

#[LiveAction]
public function delete(#[LiveArg] int $id): void
{
    // With typed argument via data-live-id-param="123"
}

Calling Actions from Twig

{# Button click #}
<button data-action="live#action" data-live-action-param="save">Save</button>

{# With arguments #}
<button
    data-action="live#action"
    data-live-action-param="delete"
    data-live-id-param="{{ item.id }}"
>Delete</button>

{# Form submit (prevent default) #}
<form data-action="live#action:prevent" data-live-action-param="submit">

{# Same thing with the helper #}
<button {{ live_action('delete', {id: item.id}) }}>Delete</button>
<button {{ live_action('save', {}, {debounce: 300}) }}>Save</button>

{# Since Symfony UX 3.6+: spread it into a Twig component tag #}
<twig:Button {{ ...live_action('save') }}>Save</twig:Button>

Downloads, Removal and Skipped Renders (LiveResponse)

Since Symfony UX 3.5+, a LiveAction (or LiveListener) can return a LiveResponse instead of only re-rendering:

use Symfony\UX\LiveComponent\LiveResponse;

#[LiveAction]
public function export(UrlGeneratorInterface $urlGenerator): LiveResponse
{
    // Preferred: the browser downloads from a route, natively and without buffering
    return LiveResponse::downloadUrl($urlGenerator->generate('app_report_download'));
}

LiveResponse::downloadFile($content, 'report.csv', 'text/csv') sends the content itself when no URL can serve it, and LiveResponse::remove() takes the component off the page (see references/api.md). Downloads keep the component state and re-render it. remove() disconnects the component; style [data-live-removing] to animate it out. Since Symfony UX 3.8+, LiveResponse::noRender() updates the state without rendering the template, for an action that changes nothing visible (mark as read, save a draft).

The default action and GET requests reject a LiveResponse with a LogicException: return it from a LiveAction or LiveListener called over POST.

Loading States

Show visual feedback during AJAX re-renders:

{# Add/remove class while loading #}
<div data-loading="addClass(opacity-50)">
<div data-loading="removeClass(hidden)">

{# Show/hide element while loading #}
<span data-loading="show">Loading...</span>
<div data-loading="hide">Content</div>

{# Disable button while loading #}
<button data-loading="addAttribute(disabled)">Submit</button>

{# Scoped to specific action or model #}
<span data-loading="action(save)|show">Saving...</span>
<span data-loading="model(query)|show">Searching...</span>

{# Delay before showing (avoid flicker on fast responses) #}
<span data-loading="delay(300)|show">Loading...</span>

Since Symfony UX 3.1+, while a request is running, the root element also carries aria-busy="true". Style it directly, and assistive technologies announce the busy region:

<div {{ attributes.defaults({class: 'aria-busy:opacity-50'}) }}>   {# Tailwind #}
[aria-busy="true"] { opacity: .5; pointer-events: none; }

Form Integration

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class RegistrationForm extends AbstractController
{
    use DefaultActionTrait;
    use ComponentWithFormTrait;

    #[LiveProp]
    public ?User $initialFormData = null;

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(UserType::class, $this->initialFormData);
    }

    #[LiveAction]
    public function save(EntityManagerInterface $em): Response
    {
        $this->submitForm();
        $user = $this->getForm()->getData();
        $em->persist($user);
        $em->flush();

        return $this->redirectToRoute('app_success');
    }
}
<div {{ attributes }}>
    {{ form_start(form, {
        attr: {
            'data-action': 'live#action:prevent',
            'data-live-action-param': 'save'
        }
    }) }}

    {{ form_row(form.email) }}
    {{ form_row(form.password) }}

    <button type="submit" data-loading="addAttribute(disabled)">Register</button>

    {{ form_end(form) }}
</div>

Real-time Validation

ComponentWithFormTrait adds data-model="on(change)|*" to the <form> and validates each field once it changes, with zero extra markup. To validate while typing, override the modifier on the form:

{{ form_start(form, {attr: {'data-model': 'debounce(300)|*'}}) }}

Component Communication

Emit Events (Child to Parent)

use Symfony\UX\LiveComponent\ComponentToolsTrait;

#[AsLiveComponent]
final class ChildComponent
{
    use DefaultActionTrait;
    use ComponentToolsTrait;

    #[LiveAction]
    public function save(): void
    {
        // ... save logic
        $this->emit('itemSaved', ['id' => $this->item->getId()]);
    }
}

Listen to Events (Parent)

use Symfony\UX\LiveComponent\Attribute\LiveListener;

#[AsLiveComponent]
final class ParentComponent
{
    use DefaultActionTrait;

    #[LiveListener('itemSaved')]
    public function onItemSaved(#[LiveArg] int $id): void
    {
        // Component re-renders automatically after this method
    }
}

Browser Events (LiveComponent to Stimulus)

$this->dispatchBrowserEvent('modal:close');
<!-- Stimulus picks it up -->
<div data-action="modal:close@window->modal#close">

Polling

Auto-refresh a component on a timer:

{# Default: every 2 seconds #}
<div {{ attributes }} data-poll>

{# Custom interval: name $render explicitly #}
<div {{ attributes }} data-poll="delay(5000)|$render">

{# Call a LiveAction on each poll #}
<div {{ attributes }} data-poll="refresh">
<div {{ attributes }} data-poll="delay(10000)|refresh">

Lazy / Deferred Loading

{# Load component after page renders (deferred AJAX call) #}
<twig:HeavyComponent loading="defer" />

{# Load when element scrolls into viewport (IntersectionObserver) #}
<twig:HeavyComponent loading="lazy" />

{# Placeholder while loading #}
<twig:HeavyComponent loading="lazy">
    <twig:block name="loadingContent"><div>Loading...</div></twig:block>
</twig:HeavyComponent>

{# Or a template #}
<twig:HeavyComponent loading="defer" loading-template="spinner.html.twig" />

The component can also define its own placeholder with a placeholder macro in its template:

{% macro placeholder(props) %}
    <div class="skeleton" style="height: {{ props.size * 4 }}rem"></div>
{% endmacro %}

Data Preservation

{# Prevent re-render from modifying this subtree #}
<div data-live-ignore>
    {# Third-party widget, contenteditable, etc. #}
</div>

{# Give list items a stable identity for morphing #}
{% for item in items %}
    <li id="item-{{ item.id }}">{{ item.name }}</li>
{% endfor %}

Computed Properties

Same as TwigComponent: getXxx() methods are accessible as this.xxx. Use computed.xxx for caching within a single render cycle (avoids calling the method multiple times in a loop).

public function getFilteredItems(): array
{
    return array_filter($this->items, fn($i) => $i->isActive());
}
{# Uncached -- called each time #}
{% for item in this.filteredItems %}

{# Cached within this render #}
{% for item in computed.filteredItems %}

Key Principles

Every interaction is a server round-trip. Rather than a client-side framework, LiveComponent is server-driven. Each re-render sends the full component state to the server, re-executes PHP, and morphs the DOM. For high-frequency interactions (drag-and-drop, real-time drawing), use Stimulus instead.

Keep components small. Large components with many LiveProps and complex templates are slow to re-render. Split into smaller, focused components that communicate via emit/listen.

Use norender and on(change) to reduce requests. Save server calls: debounce text inputs, and bind on change for fields where feedback can wait until the user leaves the field.

{{ attributes }} on root element is non-negotiable. It attaches the live Stimulus controller that drives the whole component.

References

See Also

  • twig-component: props, blocks and attributes, the base every LiveComponent builds on
  • ux-map: ComponentWithMapTrait updates a map when LiveProps change
  • ux-upload: ComponentWithUploadTrait uploads files straight into the component, before any form submit
  • ux-pagination: ComponentWithPaginationTrait for reactive filtered lists
  • ux-chartjs: charts that update when the component re-renders
  • ux-autocomplete: autocomplete fields inside ComponentWithFormTrait forms
  • ux-icons: icons re-render with the component like any Twig markup
Files (symfony-ux-skills)
  • references
    • api.md 15.9 KB
      Loading…
    • gotchas.md 11.1 KB
      Loading…
    • patterns.md 17.5 KB
      Loading…
  • SKILL.md 15.1 KB
    ---
    name: live-component
    description: 'Symfony UX LiveComponent: live search, live filters, dependent selects and form validation as users type. Use for reactive PHP and Twig components, #[AsLiveComponent], LiveProp, LiveAction, data-model, loading states, emit/listen, lazy rendering and LiveResponse downloads.'
    license: MIT
    metadata:
      author: Simon André
      url: https://smnandre.dev
    ---
    
    # LiveComponent
    
    TwigComponents that re-render dynamically via AJAX. Build reactive UIs in PHP + Twig with zero JavaScript. Every user interaction triggers a server round-trip that re-renders the component and morphs the DOM.
    
    ## When to Use LiveComponent
    
    Use LiveComponent when a component's output depends on user interaction: search results that update as you type, forms with real-time validation, filters that refine a list, anything where the UI needs to change based on user input and that change requires server-side data or logic.
    
    If the component never re-renders after initial load, use TwigComponent instead (lighter, rendered once). If the interaction is purely client-side (toggle, animation), use Stimulus instead.
    
    ## Installation
    
    ```bash
    composer require symfony/ux-live-component
    ```
    
    ## Quick Reference
    
    ```
    #[AsLiveComponent]           Make component live (re-renderable via AJAX)
    #[LiveProp]                  State that persists across re-renders
    #[LiveProp(writable: true)]  State that the frontend can modify
    #[LiveAction]                Server method callable from frontend
    data-model="prop"            Two-way bind input to LiveProp
    data-action="live#action"    Call LiveAction on event
    data-loading="..."           Show/hide/style elements during AJAX
    {{ attributes }}             REQUIRED on root element (wires the Stimulus controller)
    ```
    
    ## Basic Example
    
    ```php
    // src/Twig/Components/Counter.php
    namespace App\Twig\Components;
    
    use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
    use Symfony\UX\LiveComponent\Attribute\LiveProp;
    use Symfony\UX\LiveComponent\Attribute\LiveAction;
    use Symfony\UX\LiveComponent\DefaultActionTrait;
    
    #[AsLiveComponent]
    final class Counter
    {
        use DefaultActionTrait;
    
        #[LiveProp]
        public int $count = 0;
    
        #[LiveAction]
        public function increment(): void
        {
            $this->count++;
        }
    
        #[LiveAction]
        public function decrement(): void
        {
            $this->count--;
        }
    }
    ```
    
    ```twig
    {# templates/components/Counter.html.twig #}
    <div {{ attributes }}>
        <button data-action="live#action" data-live-action-param="decrement">-</button>
        <span>{{ count }}</span>
        <button data-action="live#action" data-live-action-param="increment">+</button>
    </div>
    ```
    
    **Critical:** The root element must render `{{ attributes }}`. This injects the Stimulus `data-controller="live"` attribute that makes the whole system work: every re-render depends on it.
    
    ## LiveProp
    
    State that persists between AJAX re-renders. Props are serialized to the frontend and sent back on every request.
    
    ### Basic Props
    
    ```php
    #[LiveProp]
    public string $query = '';
    
    #[LiveProp]
    public int $page = 1;
    
    #[LiveProp]
    public ?User $user = null;  // Entities auto-hydrate by ID
    ```
    
    ### Writable Props (Two-way Binding)
    
    Only writable props can be modified from the frontend via `data-model`:
    
    ```php
    #[LiveProp(writable: true)]
    public string $search = '';
    
    // Writable with specific fields for objects
    #[LiveProp(writable: ['email', 'name'])]
    public User $user;
    ```
    
    ### URL Binding
    
    Sync a prop to a URL query parameter: enables bookmarkable/shareable state:
    
    ```php
    #[LiveProp(writable: true, url: true)]
    public string $query = '';
    // URL becomes: ?query=search+term
    
    // Custom parameter name
    use Symfony\UX\LiveComponent\Metadata\UrlMapping;
    
    #[LiveProp(writable: true, url: new UrlMapping(as: 'q'))]
    public string $query = '';
    // URL becomes: ?q=search+term
    ```
    
    ### Hydration
    
    Doctrine entities auto-hydrate by ID. For custom types:
    
    ```php
    #[LiveProp(hydrateWith: 'hydrateStatus', dehydrateWith: 'dehydrateStatus')]
    public Status $status;
    
    public function hydrateStatus(string $value): Status
    {
        return Status::from($value);
    }
    
    public function dehydrateStatus(Status $status): string
    {
        return $status->value;
    }
    ```
    
    ## Data Binding (data-model)
    
    Bind inputs to writable LiveProps. When the input changes, the component re-renders with the new value. For a filter bound to the URL, see the [live search example](references/patterns.md#live-search).
    
    ```twig
    {# Re-render as the user types (default, debounced) #}
    <input type="text" data-model="search">
    
    {# Custom debounce -- wait 300ms after last keystroke #}
    <input type="text" data-model="debounce(300)|search">
    
    {# Only update on the "change" event (blur or Enter for text inputs) #}
    <input type="text" data-model="on(change)|search">
    
    {# Update model but don't re-render yet #}
    <input type="text" data-model="norender|search">
    
    {# Checkbox, radio, select #}
    <input type="checkbox" data-model="enabled">
    <select data-model="category">
        <option value="1">Category 1</option>
    </select>
    ```
    
    ### Validation Modifiers
    
    ```twig
    {# Only update the model when input meets criteria #}
    <input data-model="min_length(3)|search">
    <input data-model="max_length(100)|bio">
    <input type="number" data-model="min_value(0)|quantity">
    <input type="number" data-model="max_value(999)|price">
    ```
    
    ## LiveAction
    
    Server methods callable from the frontend:
    
    ```php
    #[LiveAction]
    public function save(): void
    {
        // Called via data-action="live#action" data-live-action-param="save"
    }
    
    #[LiveAction]
    public function delete(#[LiveArg] int $id): void
    {
        // With typed argument via data-live-id-param="123"
    }
    ```
    
    ### Calling Actions from Twig
    
    ```twig
    {# Button click #}
    <button data-action="live#action" data-live-action-param="save">Save</button>
    
    {# With arguments #}
    <button
        data-action="live#action"
        data-live-action-param="delete"
        data-live-id-param="{{ item.id }}"
    >Delete</button>
    
    {# Form submit (prevent default) #}
    <form data-action="live#action:prevent" data-live-action-param="submit">
    
    {# Same thing with the helper #}
    <button {{ live_action('delete', {id: item.id}) }}>Delete</button>
    <button {{ live_action('save', {}, {debounce: 300}) }}>Save</button>
    
    {# Since Symfony UX 3.6+: spread it into a Twig component tag #}
    <twig:Button {{ ...live_action('save') }}>Save</twig:Button>
    ```
    
    ### Downloads, Removal and Skipped Renders (LiveResponse)
    
    Since Symfony UX 3.5+, a `LiveAction` (or `LiveListener`) can return a `LiveResponse` instead of only re-rendering:
    
    ```php
    use Symfony\UX\LiveComponent\LiveResponse;
    
    #[LiveAction]
    public function export(UrlGeneratorInterface $urlGenerator): LiveResponse
    {
        // Preferred: the browser downloads from a route, natively and without buffering
        return LiveResponse::downloadUrl($urlGenerator->generate('app_report_download'));
    }
    
    ```
    
    `LiveResponse::downloadFile($content, 'report.csv', 'text/csv')` sends the content itself when no URL can serve it, and `LiveResponse::remove()` takes the component off the page (see [references/api.md](references/api.md#liveresponse)). Downloads keep the component state and re-render it. `remove()` disconnects the component; style `[data-live-removing]` to animate it out. Since Symfony UX 3.8+, `LiveResponse::noRender()` updates the state without rendering the template, for an action that changes nothing visible (mark as read, save a draft).
    
    The default action and GET requests reject a `LiveResponse` with a `LogicException`: return it from a `LiveAction` or `LiveListener` called over POST.
    
    ## Loading States
    
    Show visual feedback during AJAX re-renders:
    
    ```twig
    {# Add/remove class while loading #}
    <div data-loading="addClass(opacity-50)">
    <div data-loading="removeClass(hidden)">
    
    {# Show/hide element while loading #}
    <span data-loading="show">Loading...</span>
    <div data-loading="hide">Content</div>
    
    {# Disable button while loading #}
    <button data-loading="addAttribute(disabled)">Submit</button>
    
    {# Scoped to specific action or model #}
    <span data-loading="action(save)|show">Saving...</span>
    <span data-loading="model(query)|show">Searching...</span>
    
    {# Delay before showing (avoid flicker on fast responses) #}
    <span data-loading="delay(300)|show">Loading...</span>
    ```
    
    Since Symfony UX 3.1+, while a request is running, the root element also carries `aria-busy="true"`. Style it directly, and assistive technologies announce the busy region:
    
    ```twig
    <div {{ attributes.defaults({class: 'aria-busy:opacity-50'}) }}>   {# Tailwind #}
    ```
    
    ```css
    [aria-busy="true"] { opacity: .5; pointer-events: none; }
    ```
    
    ## Form Integration
    
    ```php
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Form\FormInterface;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
    use Symfony\UX\LiveComponent\Attribute\LiveAction;
    use Symfony\UX\LiveComponent\Attribute\LiveProp;
    use Symfony\UX\LiveComponent\ComponentWithFormTrait;
    use Symfony\UX\LiveComponent\DefaultActionTrait;
    
    #[AsLiveComponent]
    final class RegistrationForm extends AbstractController
    {
        use DefaultActionTrait;
        use ComponentWithFormTrait;
    
        #[LiveProp]
        public ?User $initialFormData = null;
    
        protected function instantiateForm(): FormInterface
        {
            return $this->createForm(UserType::class, $this->initialFormData);
        }
    
        #[LiveAction]
        public function save(EntityManagerInterface $em): Response
        {
            $this->submitForm();
            $user = $this->getForm()->getData();
            $em->persist($user);
            $em->flush();
    
            return $this->redirectToRoute('app_success');
        }
    }
    ```
    
    ```twig
    <div {{ attributes }}>
        {{ form_start(form, {
            attr: {
                'data-action': 'live#action:prevent',
                'data-live-action-param': 'save'
            }
        }) }}
    
        {{ form_row(form.email) }}
        {{ form_row(form.password) }}
    
        <button type="submit" data-loading="addAttribute(disabled)">Register</button>
    
        {{ form_end(form) }}
    </div>
    ```
    
    ### Real-time Validation
    
    `ComponentWithFormTrait` adds `data-model="on(change)|*"` to the `<form>` and validates each field once it changes, with zero extra markup. To validate while typing, override the modifier on the form:
    
    ```twig
    {{ form_start(form, {attr: {'data-model': 'debounce(300)|*'}}) }}
    ```
    
    ## Component Communication
    
    ### Emit Events (Child to Parent)
    
    ```php
    use Symfony\UX\LiveComponent\ComponentToolsTrait;
    
    #[AsLiveComponent]
    final class ChildComponent
    {
        use DefaultActionTrait;
        use ComponentToolsTrait;
    
        #[LiveAction]
        public function save(): void
        {
            // ... save logic
            $this->emit('itemSaved', ['id' => $this->item->getId()]);
        }
    }
    ```
    
    ### Listen to Events (Parent)
    
    ```php
    use Symfony\UX\LiveComponent\Attribute\LiveListener;
    
    #[AsLiveComponent]
    final class ParentComponent
    {
        use DefaultActionTrait;
    
        #[LiveListener('itemSaved')]
        public function onItemSaved(#[LiveArg] int $id): void
        {
            // Component re-renders automatically after this method
        }
    }
    ```
    
    ### Browser Events (LiveComponent to Stimulus)
    
    ```php
    $this->dispatchBrowserEvent('modal:close');
    ```
    
    ```html
    <!-- Stimulus picks it up -->
    <div data-action="modal:close@window->modal#close">
    ```
    
    ## Polling
    
    Auto-refresh a component on a timer:
    
    ```twig
    {# Default: every 2 seconds #}
    <div {{ attributes }} data-poll>
    
    {# Custom interval: name $render explicitly #}
    <div {{ attributes }} data-poll="delay(5000)|$render">
    
    {# Call a LiveAction on each poll #}
    <div {{ attributes }} data-poll="refresh">
    <div {{ attributes }} data-poll="delay(10000)|refresh">
    ```
    
    ## Lazy / Deferred Loading
    
    ```twig
    {# Load component after page renders (deferred AJAX call) #}
    <twig:HeavyComponent loading="defer" />
    
    {# Load when element scrolls into viewport (IntersectionObserver) #}
    <twig:HeavyComponent loading="lazy" />
    
    {# Placeholder while loading #}
    <twig:HeavyComponent loading="lazy">
        <twig:block name="loadingContent"><div>Loading...</div></twig:block>
    </twig:HeavyComponent>
    
    {# Or a template #}
    <twig:HeavyComponent loading="defer" loading-template="spinner.html.twig" />
    ```
    
    The component can also define its own placeholder with a `placeholder` macro in its template:
    
    ```twig
    {% macro placeholder(props) %}
        <div class="skeleton" style="height: {{ props.size * 4 }}rem"></div>
    {% endmacro %}
    ```
    
    ## Data Preservation
    
    ```twig
    {# Prevent re-render from modifying this subtree #}
    <div data-live-ignore>
        {# Third-party widget, contenteditable, etc. #}
    </div>
    
    {# Give list items a stable identity for morphing #}
    {% for item in items %}
        <li id="item-{{ item.id }}">{{ item.name }}</li>
    {% endfor %}
    ```
    
    ## Computed Properties
    
    Same as TwigComponent: `getXxx()` methods are accessible as `this.xxx`. Use `computed.xxx` for caching within a single render cycle (avoids calling the method multiple times in a loop).
    
    ```php
    public function getFilteredItems(): array
    {
        return array_filter($this->items, fn($i) => $i->isActive());
    }
    ```
    
    ```twig
    {# Uncached -- called each time #}
    {% for item in this.filteredItems %}
    
    {# Cached within this render #}
    {% for item in computed.filteredItems %}
    ```
    
    ## Key Principles
    
    **Every interaction is a server round-trip.** Rather than a client-side framework, LiveComponent is server-driven. Each re-render sends the full component state to the server, re-executes PHP, and morphs the DOM. For high-frequency interactions (drag-and-drop, real-time drawing), use Stimulus instead.
    
    **Keep components small.** Large components with many LiveProps and complex templates are slow to re-render. Split into smaller, focused components that communicate via emit/listen.
    
    **Use `norender` and `on(change)` to reduce requests.** Save server calls: debounce text inputs, and bind on `change` for fields where feedback can wait until the user leaves the field.
    
    **`{{ attributes }}` on root element is non-negotiable.** It attaches the `live` Stimulus controller that drives the whole component.
    
    ## References
    
    - [Symfony UX package page](https://ux.symfony.com/live-component) ([Markdown summary](https://ux.symfony.com/live-component.md)) · [`symfony/ux-live-component` on Packagist](https://packagist.org/packages/symfony/ux-live-component).
    - Try the [live package search](https://ux.symfony.com/live-component#demo) or browse [all LiveComponent demos by topic](references/patterns.md#official-demos).
    - For LiveProps, live actions, forms and component lifecycle, see the [Symfony UX LiveComponent documentation](https://symfony.com/bundles/ux-live-component).
    - **Full API** (props, actions, forms, events, all options): [references/api.md](references/api.md)
    - **Patterns** (search, CRUD, modals, validation, real-world examples): [references/patterns.md](references/patterns.md)
    - **Gotchas** (props, hydration, performance, common mistakes): [references/gotchas.md](references/gotchas.md)
    
    ## See Also
    
    - **twig-component**: props, blocks and attributes, the base every LiveComponent builds on
    - **ux-map**: `ComponentWithMapTrait` updates a map when LiveProps change
    - **ux-upload**: `ComponentWithUploadTrait` uploads files straight into the component, before any form submit
    - **ux-pagination**: `ComponentWithPaginationTrait` for reactive filtered lists
    - **ux-chartjs**: charts that update when the component re-renders
    - **ux-autocomplete**: autocomplete fields inside `ComponentWithFormTrait` forms
    - **ux-icons**: icons re-render with the component like any Twig markup
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.