Svelte · Middle · Question 8 of 75

How do you make class fields reactive?

class Todo {
  text = $state("");
  done = $state(false);
  toggle = () => { this.done = !this.done; };
}

Explanation

Class instances aren't proxied. The compiler turns $state fields into getters/setters. An arrow function keeps this correct when used as an event handler.

Further reading

Problem with a question

Svelte · Middle · question 8

Test yourself

Take the Svelte · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz