0
0
Svelteframework~5 mins

Why props pass data to children in Svelte

Choose your learning style9 modes available
Introduction

Props let parent components send information to their child components. This helps keep data organized and shared clearly.

When a parent component needs to show different text or images in a child component.
When you want to reuse a child component but with different data each time.
When you want to control how a child component looks or behaves from the parent.
When you want to keep your app organized by separating data and display.
When you want to update child components automatically when parent data changes.
Syntax
Svelte
<ChildComponent propName={value} />

<script>
  export let propName;
</script>

In Svelte, the parent passes data by adding attributes to the child component tag.

The child uses export let to declare which props it expects.

Examples
Parent sends a string "Hello" as a prop named message.
Svelte
<Child message="Hello" />

<script>
  export let message;
</script>
Parent sends a number 5 as a prop named count.
Svelte
<Child count={5} />

<script>
  export let count;
</script>
Parent sends an object userObject as a prop named user.
Svelte
<Child user={userObject} />

<script>
  export let user;
</script>
Sample Program

The parent component sends the greeting string to the child as a prop called message. The child shows this message inside a paragraph.

Svelte
<!-- Parent.svelte -->
<script>
  import Child from './Child.svelte';
  let greeting = 'Hi there!';
</script>

<Child message={greeting} />


<!-- Child.svelte -->
<script>
  export let message;
</script>

<p>{message}</p>
OutputSuccess
Important Notes

Props are read-only inside the child component. To change data, update it in the parent.

Passing props keeps components simple and focused on their job.

Summary

Props let parents send data to children in Svelte.

Children declare props with export let.

This helps build reusable and organized components.