← Back to Home
CHILD without key

Child-to-Parent with Random wire:key

Parent Component

Messages received from child: 0
Waiting for child messages...

Child Component (Random Key)

Child Component
Messages sent: 0
Component ID: qOINi54s4bhOvFVkchM4

Test Instructions

  1. 1 Open the browser console (F12)
  2. 2 Type a message in the child component input field
  3. 3 Click "Send to Parent" button
  4. 4 Check the error message in the console
What's Happening:

When you click "Send to Parent", the button triggers wire:click="sendMessage". However, the random wire:key="1654651421" causes the child component to get a new ID. Livewire then tries to find the old component ID to execute the click handler, but it no longer exists, resulting in a "Component not found" error in the console. The component is not stuck displaying the old state and is no longer usable unless the page is refreshed.

Code Structure:

Parent Component:
class Parent extends Component
{
    public $receivedMessages = [];
    public $messageCount = 0;

    #[On('child-message')]
    public function handleChildMessage($message, $from, $time)
    {
        $this->messageCount++;
        array_unshift($this->receivedMessages, [
            'message' => $message,
            'from' => $from,
            'time' => $time
        ]);
    }
}
Child Component:
class ChildWithRandomKey extends Component
{
    public $inputText = '';
    public $messageCount = 0;

    public function sendMessage()
    {
        if (trim($this->inputText)) {
            $this->messageCount++;
            $this->dispatch('child-message', [
                'message' => $this->inputText,
                'from' => $this->getId(),
                'time' => now()->format('H:i:s')
            ]);
            $this->inputText = '';
        }
    }
}
Blade Template:
<!-- Child Component Template -->
<div wire:key="{{ rand() }}">
    <input type="text" wire:model="inputText" placeholder="Type message...">
    <button wire:click="sendMessage">Send to Parent</button>
    <span>Messages sent: {{ $messageCount }}</span>
</div>

<!-- Parent includes child -->
<livewire:child-with-random-key />

BROKEN: Random wire:key causes child components to re-initialize on every parent update!