Using #[On] in Livewire to Trigger Actions from a Button
What is #[On]
?
The #[On]
attribute allows you to bind a custom Livewire event to a component method.
It replaces the older protected $listeners
approach, making your code more declarative and readable.
Basic Example: Button Triggering a Method
Display an alert when clicking a button. 1) The Livewire Component :
use Livewire\Attributes\On;
use Livewire\Component;
class AlertComponent extends Component
{
#[On('show-alert')]
public function showAlert()
{
session()->flash('message', 'Button clicked successfully!');
}
public function render()
{
return view('livewire.alert-component');
}
}
2) The Blade View resources/views/livewire/alert-component.blade.php
:
<div>
@if (session()->has('message'))
<div class="bg-green-200 text-green-800 p-2 rounded mb-4">
{{ session('message') }}
</div>
@endif
<button
class="px-4 py-2 bg-blue-600 text-white rounded"
wire:click="$dispatch('show-alert')"
>
Click here
</button>
</div>
The button dispatches a Livewire event named show-alert
, which is captured by the component using #[On('show-alert')]
.
Advanced Example: Passing Data to the Event
#[On('notify-user')]
public function notify(string $name)
{
session()->flash('message', "Notification sent to $name!");
}
<button
wire:click="$dispatch('notify-user', 'Xetaravel')"
class="bg-indigo-600 text-white px-4 py-2 rounded"
>
Notify Alice
</button>
Conclusion
The #[On]
attribute makes your Livewire components:
- More readable
- Loosely coupled (no need for
$listeners
) - Perfect for working with dynamic events