0
0
Svelteframework~5 mins

Why components are the building blocks in Svelte

Choose your learning style9 modes available
Introduction

Components let you build small, reusable pieces of your app. They help keep your code neat and easy to manage.

When you want to split a webpage into smaller parts like header, footer, and content.
When you need to reuse a button or form in many places without rewriting code.
When you want to organize your app so each part handles its own look and behavior.
When you want to make your app easier to update by changing one component instead of many places.
Syntax
Svelte
<script>
  // JavaScript logic here
</script>

<style>
  /* CSS styles here */
</style>

<!-- HTML markup here -->
<div>
  <!-- component content -->
</div>
A Svelte component is a single file with .svelte extension.
It combines HTML, CSS, and JavaScript in one place for easy management.
Examples
A simple component that shows a greeting using a variable.
Svelte
<script>
  let name = 'Friend';
</script>

<h1>Hello {name}!</h1>
This component styles the heading text in blue.
Svelte
<style>
  h1 { color: blue; }
</style>

<h1>Blue Heading</h1>
A component with a button that updates a counter when clicked.
Svelte
<script>
  export let count = 0;
</script>

<button on:click={() => count++}>
  Clicked {count} times
</button>
Sample Program

This component shows a styled heading with a customizable title. You can reuse it anywhere by changing the title.

Svelte
<script>
  export let title = 'Welcome';
</script>

<style>
  h2 {
    color: darkgreen;
    font-family: sans-serif;
  }
</style>

<h2>{title} to my Svelte app!</h2>
OutputSuccess
Important Notes

Components help you avoid repeating code by reusing the same piece multiple times.

Each component manages its own style and logic, so changes stay local and safe.

Think of components like LEGO blocks that you snap together to build your app.

Summary

Components break your app into small, manageable parts.

They make your code reusable and easier to update.

Svelte components combine HTML, CSS, and JavaScript in one file.