Sign in
Log inSign up
Svelte Beginner Tutorial

Svelte Beginner Tutorial

Mridul Ganga's photo
Mridul Ganga
·Jan 23, 2022·

3 min read

Svelte is a front-end, open-source JavaScript framework for making interactive webpages. The general concept behind Svelte is similar to pre-existing frameworks like React and Vue in that it enables developers to make web apps. However, Svelte brings several features to the table that provides developers with a unique experience.

The three main features are:

  • Less code
  • No virtual DOM
  • Truly Reactive

What is unique about Svelte?

  • Component Framework
  • tiny and fast
  • works like a compiler
  • very optimized code
  • faster than react, vue and angular
  • no virtual dom in svelte
  • easier to learn

Component Format

<script>
    // logic goes here
</script>

<!-- markup (zero or more items) goes here -->

<style>
    /* styles go here */
</style>

In a svelte component we have the above format. The js code goes into the script tag which we have only one of. The html markup goes after that followed by the style. The filename becomes the name of the component in svelte.

Creating a new svelte project

npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev

Basics

Hello World

<h1>Hello World!</h1>

Adding Data

<script>
    let name = 'world';
</script>

<h1>Hello {name.toUpperCase()}!</h1>

Binding Input

<script>
    let name = 'world';
</script>

<input bind:value={name}>

<h1>Hello {name.toUpperCase()}!</h1>

Dynamic Attributes

<script>
    let src = '/tutorial/image.gif';
</script>

<img src={src}>

Adding Style

<p>This is a paragraph.</p>

<style>
    p {
        color: purple;
        font-weight: bold;
    }
</style>

Creating and importing a component

App.svelte

<script>
    import Nested from './Nested.svelte';
</script>

<p>This is a paragraph.</p>
<Nested/>

<style>
    p {
        color: purple;
        font-weight: bold;
    }
</style>

Nested.svelte

<p>This is another paragraph.</p>

Notice how the style was only applied to the P tag in App.svelte

Render HTML

<script>
    let string = `this string contains some <strong>HTML!!!</strong>`;
</script>

<p>{@html string}</p>

Sample App (Counter)

<script>
    let count = 0;

    function increment() {
        count+=1
    }
</script>

<button on:click={increment}>
    Clicks = {count}
</button>

Array Reactivity (assignments)

// DONT
function addNumber() {
    numbers.push(numbers.length + 1);
    numbers = numbers;
}

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

Passing Values to child component

App.svelte

<script>
    import Nested from './Nested.svelte';
</script>

<Nested num={42}/>

Nested.svelte

<script>
    export let num;
    export let attr2 = 'default';
</script>

<p>Lucky Number is {num}</p>

Conditionals

<script>
let x = 5;
</script>

{#if x > 10}
    <p>{x} is greater than 10</p>
{:else if x < 5}
    <p>{x} is less than 5</p>
{:else}
    <p>{x} is between 5 and 10</p>
{/if}

Loops using each

<script>
let numbers = [1,2,3,4,5,6,7];
</script>
<ul>
    {#each numbers as n}
        <li>{n}</li>
    {/each}
</ul>

Handling Promises

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

Handling DOM Events

<button on:click={()=>{alert("been clicked")}}>
    Click Me
</button>

Creating Custom Events

App.svelte

<script>
    import Inner from './Inner.svelte';

    function handleMessage(event) {
        alert(event.detail.text);
    }
</script>

<Inner on:message={handleMessage}/>

Inner.svelte

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

    const dispatch = createEventDispatcher();

    function sayHello() {
        dispatch('message', {
            text: 'Hello!'
        });
    }
</script>

<button on:click={sayHello}>
    Click to say hello
</button>

Stores in Svelte

svelte.dev/tutorial/writable-stores