How to focus on newly added inputs in Svelte?

Rich Harris has a nicer solution


You can use use:action:

Actions are functions that are called when an element is created.

For example:

<script>
  let tasks = [];

  function addTask() {
    tasks = [...tasks, { title: "" }];
  }
    
  function init(el){
    el.focus()
  }
</script>

{#each tasks as task}
  <input type="text" bind:value={task.title} use:init />
{/each}

<button on:click={addTask}>Add task</button>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)