This is a small demo of Svelte & SvelteKit for Koodikerho.
This part is done as a code-along using the online REPL at https://svelte.dev/repl.
<script>
let name = 'Koodikerho';
</script>
<h1>Hello {name.toUpperCase()}!</h1>
Changing things changes the output.
Template syntax: everything inside {}
in the template is intepreted as JavaScript.
<script>
let wappuLength = 0;
</script>
<h1>
Wappu kestää {wappuLength} päivää
</h1>
<button on:click={() => wappuLength++}>
Lisää yksi päivä
</button>
Explain reactivity. The output automatically reacts to state change. In React, this would require the use of hooks.
Explain event handler initialization.
Show moving it inside the script
-tag.
<script>
let wappuLength = 0;
const MAX_WAPPU_LENGTH = 20;
const handleClick = () => wappuLength++;
</script>
<button on:click={handleClick}>Lisää yksi</button>
<h1>
Wappu kestää {wappuLength} päivää
</h1>
{#if wappuLength > MAX_WAPPU_LENGTH}
<p>
Wappu on liian pitkä!
</p>
{:else}
<p>
Wappu on sopivan pituinen.
</p>
{/if}
Create a new component WappuStatus.svelte
and move logic in there.
<script>
export let wappuLength;
const MAX_WAPPU_LENGTH = 20;
</script>
<p>
Wappu kestää {wappuLength} päivää
</p>
{#if wappuLength > MAX_WAPPU_LENGTH}
<p>
Wappu on liian pitkä!
</p>
{/if}
<script>
import WappuStatus from './WappuStatus.svelte';
let wappuLength = 0;
const handleClick = () => wappuLength++;
</script>
<button on:click={handleClick}>Lisää yksi</button>
<WappuStatus {wappuLength} />
This causes a problem, explain why.
<script>
export let wappuLength;
const MAX_WAPPU_LENGTH = 20;
const isWappuTooLong = wappuLength > MAX_WAPPU_LENGTH;
</script>
<p>
Wappu kestää {wappuLength} päivää
</p>
{#if isWappuTooLong}
<p>
Wappu on liian pitkä!
</p>
{/if}
So we need to hint the compiler what we want to be reactive.
<script>
export let wappuLength;
const MAX_WAPPU_LENGTH = 20;
$: isWappuTooLong = wappuLength > MAX_WAPPU_LENGTH;
</script>
<p>
Wappu kestää {wappuLength} päivää
</p>
{#if isWappuTooLong}
<p>
Wappu on liian pitkä!
</p>
{/if}
Explain component scoped styles. Showcase how styles work in Svelte.
<script>
import WappuStatus from './WappuStatus.svelte';
let wappuLength = 0;
const handleClick = () => wappuLength++;
</script>
<button on:click={handleClick}>Lisää yksi</button>
<WappuStatus {wappuLength} />
<p>
Lohenvärinen lause
</p>
<style lang="scss">
p {
background-color: salmon;
}
</style>
Node.js & NPM, fairly recent version
npm init svelte sveltekit-demo
Pick "skeleton project" and answer no to everything for now.
- Showcase routes
- Showcase api endpoint
- Showcase page endpoint
import db from '$lib/database';
/** @type {import('./__types/[id]').RequestHandler} */
export async function get({ params }) {
// `params.id` comes from [id].js
const item = await db.get(params.id);
if (item) {
return {
body: { item }
};
}
return {
status: 404
};
}