Ali Radan
Ali Radan

Reputation: 185

How to make an input take focus in Qwik?

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

Answers (1)

falselight
falselight

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

Related Questions