Hi, I was just looking through the docs, and a super common use case for me on a page is setting the focus somewhere after I have a click event. Is there a way to deal with this in livewire, or defer to local JS? Can I defer to local after calling an event on the package? Maybe a quick docs page on this might be helpful.
Cheers
Hi @roni-estein , if I understand you correctly, that you are adding new elements and want to immediately set autofocus for them.
Please see this example:
namespace App\Http\Livewire\Foo;
use Livewire\Component;
class Bar extends Component
{
/**
* @var bool
*/
public $isOpenProfileForm = false;
/**
* @return \Illuminate\View\View
*/
public function render()
{
return view('livewire.foo.bar', [
'isOpenProfileForm' => $this->isOpenProfileForm,
]);
}
/**
* @return void
*/
public function openForm()
{
$this->isOpenProfileForm = true;
}
}
This is a simple form that simulates a situation in which, by clicking on the button, a modal window appears, where the input field will be offered to the user to fill in automatically.
<div>
<button wire:click="openForm">Edit Profile</button>
@if($isOpenProfileForm)
<div class="modal">
<input name="first_name" autofocus>
</div>
@endif
</div>
This is what you need?
Here's a way you can hook into Livewire events and do things with JS:
Blade Template:
<div class="pt-8 w-48">
<button wire:click="increment">+</button>
<button wire:click="decrement">-</button>
<input type="text">
{{ $count }}
</div>
@push('scripts')
<script>
window.addEventListener('livewire:load', () => {
@this.on('incremented', () => {
document.querySelector('input').focus()
})
})
</script>
@endpush
Relevant Parts Of Component:
public function increment()
{
$this->count++;
$this->emit('incremented');
}
Nice! That javascript solution looks perfect! I'll give it a try shortly! I think I need to re-read the docs if I missed that.
Most helpful comment
Nice! That javascript solution looks perfect! I'll give it a try shortly! I think I need to re-read the docs if I missed that.