Daniel Macak
Daniel Macak

Reputation: 17093

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

I am used to libs/frameworks like React or Angular which both have convenient ways to access actual DOM elements that belong to logical components. React has the createRef utility and Angular has among other things the template variables in combination with eg. @ViewChild.

Those references not only make it easy to access the DOM without querying the elements explicitly every time , they also stay up to date with the DOM so that they always hold reference to the current element. I just started with Svelte for my pet project but although I went through Svelte's documentation and google a lot, I didn't find anything similar in concept & usage. I suppose it might have something to do with the Svelte's runtime-less concept, but still don't know why there wouldn't be such a utility.

So the question is, is there a similar utility in Svelte?

Upvotes: 26

Views: 24679

Answers (1)

ahwayakchih
ahwayakchih

Reputation: 2371

Based on the example found at https://svelte.dev/tutorial/bind-this (thanks to @skyboyer), you can use bind:this (try in REPL):

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

    let myInput;

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

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

You can also use use:action, as seen at https://svelte.dev/docs#template-syntax-element-directives-use-action and suggested by @collardeau (try in REPL):

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

    let myInput;

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

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

Upvotes: 60

Related Questions