inputautofocussvelte

How to focus on input field loaded from component in Svelte?


After loading the component that has input filed inside it. How can I focus on that particular field?

TextField.svelte

<script>

  export let label = ''
  export let name = ''
  export let placeholder = ''
  export let value = ''

</script>

<div class="field">
  <label for={name}>{label}</label>
  <input {placeholder} type="text" {name} bind:value={value} >
  <slot></slot>
</div>

App.svelte

<script>
  import TextField from './TextField'
  import {onMount} from 'svete'

  onMount(() => {
    // This line is funny.. I know
    document.querySelector('[name="firstname"]').focus()
  })

</script>

<TextField label="First Name" name="firstname" />

Solution

  • You can get a reference to the input DOM node with bind:this and export it as a prop and use it in the parent component.

    Example

    <!-- TextField.svelte -->
    <script>
      export let label = '';
      export let name = '';
      export let placeholder = '';
      export let value = '';
      export let ref = null;
    </script>
    
    <div class="field">
      <label for={name}>{label}</label>
      <input {placeholder} type="text" {name} bind:value={value} bind:this={ref} >
      <slot></slot>
    </div>
    
    <!-- App.svelte -->
    <script>
      import TextField from './TextField.svelte';
      import { onMount } from 'svelte';
        
      let ref;
        
      onMount(() => {
        ref.focus(); 
      });      
    </script>
    
    <TextField label="First Name" name="firstname" bind:ref />