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?
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.
$$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.
AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
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/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With