Svelte logo

Svelte by Example: Components & Props

Components are reusable building blocks of a user interface. Svelte components are created in files with a .svelte extension.

In this example, we'll create a Todo component that accepts task and checked props. We'll then render it in a TodoList component.

Components can pass and receive props to and from other components with exported let variables.

Default values can be set by assigning the variable.

Components can be imported to use in other components.

Components are rendered using PascalCase.

Todo.svelte
<script>
  export let task;



  export let completed = false;
</script>

<p>
  <input type="checkbox" checked={completed}>
  {task}
</p>
TodoList.svelte
<script>
  import Todo from './Todo.svelte';
</script>

<Todo task="Mow lawn" />
<Todo task="Walk dog" />
<Todo task="Read newspaper" />

Data & its shorthand notation can also be used for props.

TodoList.svelte
<script>
  import Todo from './Todo.svelte';

  let task = "Mow lawn";
</script>

<Todo {task} />

Multiple props can be passed at once with the spread operator ....

TodoList.svelte
<script>
  import Todo from './Todo.svelte';

  let todo = {
    task: "Mow lawn",
    completed: false,
  };
</script>

<Todo {...todo} />