Is there a convenient way to reference DOM elements in Svelte components?

· · 3392 views

In frameworks like React and Angular, there are convenient methods to access DOM elements within components, such as React's createRef and Angular's template variables combined with @ViewChild. These references are easy to use and stay up to date with the DOM, always pointing to the current element.

I am new to Svelte and, despite exploring its documentation and searching online, I haven't found a similar utility. I understand that Svelte's runtime-less concept might be a factor, but I'm still unclear on why such a feature would be absent.

So, is there an equivalent way to reference DOM elements in Svelte?

0
1 Answer

You can reference DOM elements in Svelte using bind:this as shown in this example from Svelte's tutorial:

<script>
    import { onMount } from 'svelte';

    let myInput;

    onMount(() => {
        myInput.value = 'Hello world!';
    });
</script>

<input type="text" bind:this={myInput}/>

Another approach is to use use:action, as described in the Svelte documentation:

<script>
    import { onMount } from 'svelte';

    let myInput;

    function MyInput(node) {
        myInput = node;
        myInput.value = 'Hello world!';
    }
</script>

<input type="text" use:MyInput/>
0

Please login or create new account to participate in this conversation.