Chapter 3: Svelte Basics

In this chapter, we'll learn the fundamentals of creating Svelte components. You'll understand the structure of a Svelte file, how to work with templates, and how to pass data between components using props.

Anatomy of a Svelte Component

A Svelte component is a .svelte file that contains three sections: script, markup, and style. Each section is optional but often used together.

<script>
  // JavaScript code here
  let message = 'Hello, Svelte!';
</script>

<h1>{message}</h1>

<style>
  h1 {
    color: purple;
  }
</style>

Sections Explained:

  • <script>: Contains your JavaScript logic, state variables, and functions.
  • Markup: HTML template with Svelte directives and data bindings.
  • <style>: CSS scoped to this component only.

Working with Props

Props allow you to pass data from a parent component to a child component. In Svelte, you export variables to create props:

<script>
  export let name = 'World';
</script>

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

When using this component, you can pass data like this:

<Greeting name="Alice" />

Displaying Data

In your markup, use curly braces to display JavaScript expressions:

<script>
  let count = 0;
  let items = ['Apple', 'Banana', 'Orange'];
</script>

<p>Count: {count}</p>

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>

Conditional Rendering

Use the {#if} block to conditionally render elements:

<script>
  let isVisible = true;
</script>

{#if isVisible}
  <p>This is visible!</p>
{:else}
  <p>This is hidden!</p>
{/if}

Now you have the foundations for building Svelte components. In the next chapter, we'll explore more advanced component patterns!