DEV Community

V Sai Harsha
V Sai Harsha

Posted on • Edited on

Svelte.js Cheatsheet

Svelte.js is a modern JavaScript framework that simplifies web development by compiling components at build time rather than running them in the browser. This cheatsheet provides a quick reference to key concepts and features in Svelte.js for developers at beginner and intermediate levels.

Getting Started

Installation

To start using Svelte.js, you need to set up a development environment. You can create a new Svelte project using the official template:

npm create svelte@latest myapp
cd myapp
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Svelte Components

Svelte applications are built using components. Each component is defined in a .svelte file and encapsulates its HTML, CSS, and JavaScript logic.

<!-- HelloWorld.svelte -->
<script>
  let name = 'Svelte';
</script>

<h1>Hello, {name}!</h1>

<style>
  h1 {
    color: blue;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Data Binding

Variables

You can declare and use variables in your Svelte components. Variable updates automatically trigger reactivity.

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

<button on:click={() => count += 1}>Increment</button>
<p>Count: {count}</p>
Enter fullscreen mode Exit fullscreen mode

Two-Way Binding

You can achieve two-way binding using the bind directive:

<script>
  let name = 'Svelte';
</script>

<input bind:value={name} />
<p>Your name is: {name}</p>
Enter fullscreen mode Exit fullscreen mode

Conditionals and Loops

Conditional Rendering

You can conditionally render elements using {#if} and {:else}:

{#if loggedIn}
  <p>Welcome, {user.name}!</p>
{:else}
  <p>Please log in.</p>
{/if}
Enter fullscreen mode Exit fullscreen mode

List Rendering

You can loop through arrays using {#each}:

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
Enter fullscreen mode Exit fullscreen mode

Events and Event Handling

Event Listeners

You can listen for DOM events and handle them with functions:

<button on:click={handleClick}>Click Me</button>

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Event Modifiers

Svelte provides event modifiers like preventDefault and stopPropagation:

<a href="/example" on:click|preventDefault={handleClick}>
  Clicking this link won't navigate.
</a>
Enter fullscreen mode Exit fullscreen mode

Component Communication

Props

You can pass data from parent to child components using props:

<!-- Parent.svelte -->
<script>
  let message = 'Hello from Parent!';
</script>

<Child message={message} />

<!-- Child.svelte -->
<script>
  export let message;
</script>

<p>{message}</p>
Enter fullscreen mode Exit fullscreen mode

Custom Events

Child components can communicate with parents using custom events:

<!-- Child.svelte -->
<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();

  function notifyParent() {
    dispatch('customEvent', 'Data from Child');
  }
</script>

<button on:click={notifyParent}>Notify Parent</button>
Enter fullscreen mode Exit fullscreen mode
<!-- Parent.svelte -->
<script>
  let dataFromChild = '';

  function handleCustomEvent(event) {
    dataFromChild = event.detail;
  }
</script>

<Child on:customEvent={handleCustomEvent} />
<p>Data from Child: {dataFromChild}</p>
Enter fullscreen mode Exit fullscreen mode

Lifecycle Methods

Svelte components have lifecycle methods like onMount, beforeUpdate, and afterUpdate:

<script>
  import { onMount } from 'svelte';

  onMount(() => {
    console.log('Component mounted');
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Stores

Svelte provides stores for shared state management:

<script>
  import { writable } from 'svelte/store';

  const count = writable(0);

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

<button on:click={increment}>Increment</button>
<p>Count: {$count}</p>
Enter fullscreen mode Exit fullscreen mode

Routing

You can implement client-side routing in Svelte using libraries like svelte-routing.

CSS

Svelte supports scoped styles using <style> blocks within components.

Dev Tools

Svelte has a browser extension for debugging and inspecting components.

Conclusion

Svelte.js offers a straightforward and efficient way to build web applications with a focus on reactivity and simplicity. This cheatsheet covers essential concepts and features to help beginners and intermediate developers get started with Svelte development.

Estimated Reading Time: 6 minutes

Top comments (0)