← Back to Home

NESTED COMPONENTS (wire:key on root div and component)

Learn Laravel with nested components
ID: 1 | Position: 1 | Status: Pending
Extra content in div
Master Livewire wire:key with nesting
ID: 2 | Position: 2 | Status: Completed
Extra content in div
Build complex nested apps
ID: 3 | Position: 3 | Status: Pending
Extra content in div
Understand DOM state preservation
ID: 4 | Position: 4 | Status: Pending
Extra content in div

Nested Components Test

  1. 1 Type in ALL input fields (component and div inputs)
  2. 2 Check the checkboxes in the blue sections
  3. 3 Use ↑/↓ buttons to reorder items
  4. 4 Notice: ALL inputs move correctly with their items!
  5. 5 Notice: Checkboxes maintain their state!
  6. 6 Delete items - all state preserved correctly
Key Point:

Root div has wire:key, so ALL nested DOM elements preserve their state correctly during reordering!

Nested Components Code Structure:

Parent Component (ComplexTodoList):
class ComplexTodoList extends Component
{
    public $todos = [];

    #[On('toggle-todo')]
    public function toggleTodo($todoId) { /* handles child events */ }

    #[On('move-up')]
    public function moveUp($todoId) { /* reorder logic */ }
}
Child Component (TodoItem):
class TodoItem extends Component
{
    public $todo, $index, $totalCount;

    public function toggleCompleted() {
        $this->dispatch('toggle-todo', $this->todo['id']);
    }
}
Template with wire:key on Root Div and Component:
@foreach($todos as $index => $todo)
    <!-- Root container div WITH wire:key -->
    <div wire:key="todo-item-{{ $todo['id'] }}" class="bg-gradient-to-r from-purple-50 to-blue-50 p-2 rounded-lg">
        <!-- Inner wrapper div without wire:key -->
        <div class="bg-white rounded border p-1">
            <!-- Nested Livewire component with wire:key -->
            <livewire:todo-item
                :todo="$todo"
                :index="$index"
                :totalCount="count($todos)"
                wire:key="todo-item-{{ $todo['id'] }}"
            />
        </div>

        <!-- Additional nested div without wire:key -->
        <div class="mt-2 px-2 py-1 bg-purple-50">
            <span>ID: {{ $todo['id'] }}</span> |
            <input type="text" placeholder="State preserved!" class="ml-2" />
        </div>

        <!-- Another div without wire:key -->
        <div class="mt-1 px-2 py-1 bg-blue-50">
            <input type="checkbox" />
            <label>Check me - state preserved!</label>
        </div>
    </div>
@endforeach

CORRECT: Root div has wire:key with stable todo ID

CORRECT: Livewire component has wire:key with stable todo ID

CORRECT: All nested divs inherit proper DOM tracking from root div