Passing Data with Props in Svelte

Introduction to Props in Svelte

Welcome to the first lesson of the "Component Communication & Events in Svelte" course. In this lesson, we will focus on component communication, specifically how to pass data from a parent component to a child component using props.

Props (short for "properties") are a way to share data between components. Think of props as passing a note from one person to another—the parent component writes the note (data), and the child component reads it. This is a fundamental concept in Svelte and is essential for building scalable and maintainable applications.

In this lesson, we’ll explore how to define and pass props, including complex data types like objects, and how to use them effectively in your components. By the end, you’ll be able to pass data from a parent component to a child component, just like in the example.

Defining and Passing Props

To pass data from a parent component to a child component, you first need to define the props in the child component. In Svelte 5, you can use the $props() function to access the props passed from the parent.

Let’s start with a simple example: passing a string prop.

Svelte
<!-- Parent.svelte -->
<script>
  import Child from './Child.svelte';
</script>

<Child placeholder="Enter your name" />
<!-- Child.svelte -->
<script>
  let { placeholder } = $props();
</script>

<input type="text" placeholder={placeholder} />

In this example, the parent component (Parent.svelte) passes a placeholder prop to the child component (Child.svelte). The child component extracts placeholder from $props() and applies it to the <input> field. When you run this code, the input field will display the placeholder text "Enter your name."

In Svelte, the $props() function allows a child component to access props passed from its parent. However, it’s important to note that $props() itself does not trigger reactivity. When a parent component updates a prop, the child component receives the new value, but the $props() function doesn’t automatically cause a reactive update like $state. To ensure that changes to props are properly tracked within the child component, you can either destructure the needed values or assign them to $state. This approach helps maintain reactivity and ensures your components stay in sync with their data sources.

Forwarding Extra Props with ...rest

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal