Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
It’s not just variables that can be made reactive — in Svelte, we can also make properties of classes reactive.
Let’s make the width
and height
properties of our Box
class reactive:
App
class Box {
width = $state(0);
height = $state(0);
area = 0;
// ...
}
Now, when we interact with the range inputs or click the ‘embiggen’ button, the box reacts.
We can also use $derived
, so that box.area
updates reactively:
App
class Box {
width = $state(0);
height = $state(0);
area = $derived(this.width * this.height);
// ...
}
In addition to
$state
and$derived
, you can use$state.raw
and$derived.by
to define reactive fields.
previous next
<script>
const MAX_SIZE = 200;
class Box {
width = 0;
height = 0;
area = 0;
constructor(width, height) {
this.width = width;
this.height = height;
}
embiggen(amount) {
this.width += amount;
this.height += amount;
}
}
const box = new Box(100, 100);
</script>
<label>
<input type="range" bind:value={box.width} min={0} max={MAX_SIZE} />
{box.width}
</label>
<label>
<input type="range" bind:value={box.height} min={0} max={MAX_SIZE} />
{box.height}
</label>
<button onclick={() => box.embiggen(10)}>embiggen</button>
<hr>