0
0
SvelteHow-ToBeginner · 3 min read

How to Create a Counter in Svelte: Simple Step-by-Step Guide

In Svelte, create a counter by declaring a let variable for the count and updating it with event handlers like on:click. Use curly braces {} to display the variable in your component's HTML.
📐

Syntax

To create a counter in Svelte, you declare a reactive variable using let. You then update this variable inside event handlers such as on:click. The variable's value is displayed in the HTML using curly braces {}.

  • let count = 0; declares the counter variable.
  • on:click={() => count++} increases the count when clicked.
  • {count} shows the current count in the UI.
svelte
<script>
  let count = 0;
</script>

<button on:click={() => count++}>
  Count is {count}
</button>
Output
A button labeled 'Count is 0' that increments the number each time it is clicked.
💻

Example

This example shows a simple counter button that starts at zero and increases by one each time you click it. It demonstrates Svelte's reactive variables and event handling.

svelte
<script>
  let count = 0;
</script>

<button on:click={() => count++} aria-label="Increment counter">
  Count is {count}
</button>
Output
A button labeled 'Count is 0' that updates to 'Count is 1', 'Count is 2', etc., on each click.
⚠️

Common Pitfalls

Common mistakes when creating a counter in Svelte include:

  • Using const instead of let for the counter variable, which prevents updates.
  • Not using the on:click event properly, so clicks don't change the count.
  • Trying to update the variable without using reactive syntax, which Svelte won't track.

Always use let for variables that change and update them inside event handlers.

svelte
<script>
  // Wrong: count is constant and cannot change
  const count = 0;
</script>
<button on:click={() => count++}>
  Count is {count}
</button>

<script>
  // Right: count is let and updates correctly
  let count = 0;
</script>
<button on:click={() => count++}>
  Count is {count}
</button>
📊

Quick Reference

Summary tips for creating counters in Svelte:

  • Use let to declare variables that change.
  • Use on:click to handle button clicks.
  • Display variables inside {} in your HTML.
  • Ensure accessibility by adding aria-label to buttons.

Key Takeaways

Use let to declare a reactive counter variable in Svelte.
Update the counter inside an on:click event handler to change its value.
Display the counter value in the UI using curly braces {count}.
Avoid using const for variables that need to change.
Add accessibility labels like aria-label to interactive elements.