Note: As there are no duplicate components we don't need to give the component a key. Livewire automatically assigns a stable component ID.
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
]);
}
}
class ChildWithoutKey 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 = '';
}
}
}
<!-- Child Component Template -->
<div>
<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-without-key />
CORRECT: As there is only one component of its type, there is no need to add a wire:key let alone a random one