Alpine.js - Show an input field and add focus to it at the same time
I have a button, and when a user clicks it, an input element should be shown and it should have focus.
I tried this:
<div x-data="{ show: false }">
<input x-show="show" type="text" id="input" x-ref="input" />
<button @click="show = !show; $refs.input.focus();">Button</button>
</div>
But it does not work.
You need to use nextTick so that the reactive DOM changes resulting from show changing have been completed:
<div x-data="{ show: false }">
<input x-show="show" type="text" id="input" x-ref="input" />
<button @click="show = !show; $nextTick(() => $refs.input.focus());">Button</button>
</div>
https://github.com/alpinejs/alpine#nexttick
Please or to participate in this conversation.