0
0
SvelteHow-ToBeginner · 3 min read

How to Create a Component in Svelte: Simple Guide

In Svelte, you create a component by making a .svelte file that contains HTML, JavaScript, and CSS together. Each component is a reusable piece of UI that you can import and use in other components or your app.
📐

Syntax

A Svelte component is a single .svelte file that combines three parts:

  • Script: JavaScript code inside a <script> tag for logic and data.
  • Markup: HTML code for the UI structure.
  • Style: CSS inside a <style> tag scoped to the component.

This structure keeps everything related to the component in one place.

svelte
<script>
  // JavaScript logic here
  let name = 'world';
</script>

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

<style>
  h1 {
    color: teal;
  }
</style>
Output
Hello world! (with teal colored heading)
💻

Example

This example shows a simple Svelte component that displays a greeting message with a name variable. It demonstrates how to use script, markup, and style together.

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

<h2>Welcome to {name}!</h2>

<style>
  h2 {
    font-family: Arial, sans-serif;
    color: #ff3e00;
  }
</style>
Output
Welcome to Svelte! (orange heading with Arial font)
⚠️

Common Pitfalls

1. Forgetting to use curly braces for variables: In markup, you must wrap JavaScript variables in {} to show their values.

2. Using global CSS instead of scoped styles: Styles inside <style> are scoped to the component by default. Avoid putting styles outside or in global CSS unless needed.

3. Not exporting props: To pass data into a component, you must export variables in the script.

svelte
<!-- Wrong: missing curly braces -->
<h1>Hello name!</h1>

<!-- Right: use curly braces -->
<h1>Hello {name}!</h1>

<!-- Exporting a prop -->
<script>
  export let title;
</script>
<h1>{title}</h1>
📊

Quick Reference

  • Create a .svelte file for each component.
  • Use <script> for logic and data.
  • Write HTML markup directly in the file.
  • Use {variable} to insert JavaScript values.
  • Style with <style> scoped to the component.
  • Export props with export let propName; to accept inputs.

Key Takeaways

Create components as single .svelte files combining script, markup, and style.
Use curly braces {} to insert JavaScript variables in markup.
Export variables with 'export let' to accept props from parent components.
Styles inside