Concepts
Basics
Variables
https://svelte.dev/docs/svelte/$state
https://svelte.dev/docs/svelte/$derived
let state_var = $state(start_value)
let derived_var = $derived(state_var * 2)
let derived_var_by_func = $derived.by(() => {
// For more complicated logic
return state_var * 2
)
Apparently you should prefer to use $derived over $effect because DOM changes should not be done in $effect.
Bind values to variables
https://svelte.dev/docs/svelte/bind
You can bind values directly to input elements, so that the variable changes when the input value changes.
This can be done on text inputs, number inputs, checkbox inputs.
let value = $state(1)
<input type="number" bind:value={message} />
You can also use function bindings to use getters and setters.
Props
https://svelte.dev/docs/svelte/$props
Props are used on children components. Parent components can instanciate children components with arguments.
Values should always be changed in the parent element (TODO why?), so pass down functions to the children to allow value mutation. Sometimes, the displayed values are mapped or filtered values, so the mutation should not be done on the props directly.
let {my_prop1, my_prop2}: {my_prop1: my_prop1_type, my_prop2: my_prop2_type} = $props()
Use components like this:
<MyComponent my_prop1="value" my_prop2={1+1} />
<MyComponent {...my_prop1, my_prop2} />
If else
https://svelte.dev/docs/svelte/if
TODO
Each
https://svelte.dev/docs/svelte/each
TODO
Intermediate
Snippets
Define a snippet with
{#snippet snippet_name(snippet_arg: snippet_arg_type, ...)}
<div>{snippet_arg}</div>
{/snippet}
Use snippet with
{@render snippet_name('my_value')}
Classes on condition
https://svelte.dev/docs/svelte/class
You can use classes on elements conditionally
<script>
let my_boolean = $state(true)
</script>
<div
class={["this class is always applied", {"this class is applied if the condition is true": my_boolean}]}
>
My Text
</div>
Advanced
Debugging
You can use https://svelte.dev/docs/svelte/$inspect to console log values when they change.
let my_var = $state(1)
$inspect(my_var)
Transition and animation
https://svelte.dev/docs/svelte/transition