Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
Skocdopole Avatar asked Oct 13 '19 10:10

Skocdopole


People also ask

How do you grab elements from DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable.

What is $$ in Svelte?

$$props references all props that are passed to a component, including ones that are not declared with export . It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component.

Which method is used to add components or elements to the DOM?

AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .


1 Answers

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/>
like image 153
ahwayakchih Avatar answered Oct 18 '22 07:10

ahwayakchih