Reputation: 185
I'm using Qwik. I have a button. When I click it, an input is shown. How can I make the input take focus too?
const showInput = useSignal(false)
const handleClick = () => {
showInput.value = !showInput.value
// I'm stuck here. How can I make the input take focus?
}
return <>
<button onClick$={handleClick}>Show input</button
<input class={showInput.value ? " " : "hidden"} />
</>
Upvotes: 0
Views: 74
Reputation: 860
const showInput = useSignal(false)
const ref = useSignal<HTMLInputElement>();
const handleClick = $(() => {
showInput.value = !showInput.value;
const id = setTimeout(() => ref.value?.focus(), 0);
return () => clearTimeout(id);
})
return <>
<button onClick$={handleClick}>Show input</button>
<input ref={ref} class={{"hidden": !showInput.value}} />
</>
This is because the focus should occur after the element becomes visible. One of the options is setTimeout
Upvotes: 1