Alexander Schatzberg
Alexander Schatzberg

Reputation: 23

Element not becoming reactive in a svelte file

As a person who usually works on the backend, I decided to try and build a website for fun. I'm using SvelteKit, and I ended up wanting some reactivity. I decided to put together a 'hello world', just to make sure everything was working and there seems to be an issue. This is code taken directly from the svelte website.

src/test/+page.svelte

<script>
    let count = 0;

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

<button on:click={handleClick}>
    Clicked {count}
    {count === 1 ? "time" : "times"}
</button>

svelte.config.js

import adapter from "@sveltejs/adapter-auto";
import { vitePreprocess } from "@sveltejs/kit/vite";

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://kit.svelte.dev/docs/integrations#preprocessors
    // for more information about preprocessors
    preprocess: vitePreprocess(),

    kit: {
        adapter: adapter(),
    },
    static: "static",
};

export default config;

If there are any other files that would be helpful, please let me know.

I've tried putting together a super simple demo that I know should work, but it didn't. I'm not very experienced in this realm, so there could be a very obvious fix that I'm not seeing.

Upvotes: 0

Views: 343

Answers (1)

KellyCMI
KellyCMI

Reputation: 21

If you want to see some reactivity you just have to add it ;)

To let Svelte know that we want to set reactive statement we use '$:' symbol. It can be a simple assingment but also a block of code.

Try this classic:

<script>
let count = 0;

function handleClick() {
    count += 1;
}

$: doubled = count *2 ;
<button on:click={handleClick}>
    Clicked {count}
    {count === 1 ? "time" : "times"}
</button>
<p>
    doubled value is: {doubled}
</p>

More explanation you'll find in this tutorial: https://svelte.dev/tutorial/reactive-assignments

Upvotes: 2

Related Questions