How to focus back on input after clicking button in Svelte?

Viewed 1033

Use Case

I am building a chat application so whenever a user types in a message in the chat box and clicks on send, ideally it should focus back on the input. Currently, this requires the user to click on the input again to start typing.

How can this be achieved in Svelte? I tried to use the bind:this and use: directives.

Edit: This is a Svelte Sapper project.

1 Answers

You can easily create a reference to your rendered component using bind:this={myComponentRef}. Then to focus it, just call myComponentRef.focus():

<script>
  let message = ""

  let inputRef

  const onSend = () => {
    inputRef.focus()
  }
</script>

<input bind:this={inputRef} value={message}>
<button on:click={onSend}>Send Message</button>

Have a look to the REPL.

Related