Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Components

A component is a self-contained piece of interface: a button, a card, a list row. You write it once and put it on the page as many times as needed. In Svelte every component is a separate file with the .svelte extension.

Three parts of a file

A component file may contain three parts, each optional:

PartWhat it holds
<script>variables, functions, imports
markupHTML with expressions in curly braces
<style>CSS that applies only inside the component

Creating a component

There is no special command — create the folder src/lib/components and the file TodoItem.svelte in it:

<!-- src/lib/components/TodoItem.svelte -->
<script>
  let text = 'Buy bread';
</script>
 
<li>{text}</li>
 
<style>
  li {
    padding: 4px 0;
    color: #333;
  }
</style>

The component renders a list item with the task text. A variable from <script> is available in the markup through curly braces, and the li style affects only this component.

Rendering on a page

To use a component, import it in another component and write it as a tag:

<!-- src/routes/+page.svelte -->
<script>
  import TodoItem from '$lib/components/TodoItem.svelte';
</script>
 
<h1>My tasks</h1>
<ul>
  <TodoItem />
  <TodoItem />
</ul>

At http://localhost:5173 two identical "Buy bread" items appear under the heading. Later, in the lesson on props, each item will get its own text.

Component names

The import name is the component's name, and it is written with a capital letter: TodoItem, TodoList. Svelte tells components from HTML tags by that capital letter: <button> is a regular element, <Button> is a component.

Order of parts

Usually <script> comes first, then the markup, then <style>. The order can change, but a file may have only one regular <script> block and one <style>.

Common mistake

Naming a component with a lowercase letter:

<script>
  import todoItem from '$lib/components/TodoItem.svelte';
</script>
 
<todoItem />

Svelte treats <todoItem /> as an unknown HTML tag, and nothing appears on the page. Always start the name of an imported component with a capital letter.

Thanks for reading!

Donate to the site — we work hard for you.