Svelte Basics🔗

Notes on using Svelte.js


Variables are automatically reactive in .svelte files.

	let count = 0;

	function incrementCount() {
		// event handler code goes here
		count += 1

<button on:click={incrementCount}>
	Clicked {count} {count === 1 ? 'time' : 'times'}

Note that sveltes reactivity only happens on re-assignments to variables. so methods like push() pop() do not cause any reactivity. The way around this is to clone and reassign arrays making use of the spread operator:

function addNumber() {
	numbers = [...numbers, numbers.length + 1];

Reactive Declarations🔗

aka computed values can be created with the $ syntax .e.g

   let count = 0;
   $: doubled = count * 2

   function handleClick() {
   	count += 1;

<button on:click={handleClick}>
   Clicked {count} {count === 1 ? 'time' : 'times'}


Note: you could alternatively write {count * 2} .

We’re not limited to declaring reactive values — we can also run arbitrary statements reactively. For example, we can log the value of count whenever it changes:

$: console.log(`the count is ${count}`);

You can easily group statements together with a block:

$: {
	console.log(`the count is ${count}`);
	alert(`I SAID THE COUNT IS ${count}`);

You can even put the $: in front of things like if blocks:

$: if (count >= 10) {
	alert(`count is dangerously high!`);
	count = 9;


props for components are exposed using the export keyword e.g

// Nested.svelete

	export let answer;

<p>The answer is {answer}</p>

	import Nested from './Nested.svelte';

<Nested answer={42}/>

this renders The answer is 42

Default props can e applied by defining it at the export

// Nested.svelete

	export let answer =42;

<p>The answer is {answer}</p>

Svelte Syntax🔗


{#each things as thing (}
	<Thing name={}/>


a.k.a, async rendering

{#await promise}
{:then number}
	<p>The number is {number}</p>
{:catch error}
	<p style="color: red">{error.message}</p>

Two-way Data Binding🔗

Two way data binding works very similar to Vue.js. element values can be binded both ways to read and edit data

	let name = 'world';

<input bind:value={name}>

<h1>Hello {name}!</h1>

bind works across pretty much everything you expect it to including textarea input select and even contenteditable on divs

Svelte provides reactive bindings to audio and video elements The complete set of bindings for <audio> and <video> is as follows — six readonly bindings…

…and five two-way bindings:

Videos additionally have readonly videoWidth and videoHeight bindings.

Svelte also handle converting values from numbers to strings, this is helpful when you’re dealing with numeric inputs — type="number" and type="range" — as it means you have to remember to coerce input.value before using it.

	let a = 1;

<input type=number bind:value={a} min=0 max=10>
<input type=range bind:value={a} min=0 max=10>



{@debug user}

// these do the same things