tezvyn:

Svelte Props: Passing Data with `export let`

AI-drafted, machine-checkedSource: svelte.devbeginner
Svelte Props: Passing Data with `export let`

In Svelte, `export let` turns a variable into a prop, letting a parent component pass data down. It's how you pass a `userName` to a `ProfileCard` component. The footgun: forgetting `export` creates a private variable, not a prop, so data isn't received.

WHY IT EXISTS Components are the building blocks of applications, but they are only reusable if they can be configured from the outside. Hardcoding data inside a component, like a user's name, means it can only ever display that one user. Props exist to make components flexible by allowing parent components to pass data into them.

THE MENTAL MODEL Think of export let as declaring a public API for your component. In a normal JavaScript module, the export keyword makes a function or variable available for other modules to import. In Svelte, export let inside a <script> tag makes a variable a "prop" that can be set by a parent component using it in its markup.

HOW IT WORKS Svelte repurposes the export keyword to mark a variable declaration as a component property. When you write export let name; in a child component, you're telling Svelte: "This component accepts a prop called name." A parent component can then pass a value to it like an HTML attribute: <ChildComponent name="Alice" />. You can also provide a default value, like export let name = 'Guest';, which will be used if the parent doesn't provide the prop.

WHEN TO USE IT Use export let for one-way data flow from a parent to a child. This is the fundamental way to pass data down the component tree. It's perfect for configuring child components, such as passing an image URL to an Avatar component or a list of items to a TodoList component. This is the standard method for declaring props in Svelte 4 and earlier.

WHEN NOT TO USE IT For data that should be private to a component's internal state, use a regular let declaration without export. The biggest footgun is forgetting export; the variable will exist, but it won't be a prop, and the component will silently fail to receive data from its parent. For new Svelte 5 projects, the recommended approach is to use runes, like $props(), to handle props.

ONE CANONICAL EXAMPLE A parent App.svelte uses a Greeting.svelte component. In Greeting.svelte: <script> export let name = 'World'; </script> <h1>Hello, {name}!</h1>

In App.svelte: <script> import Greeting from './Greeting.svelte'; </script> <Greeting name="Alex" />

This renders an <h1> tag containing "Hello, Alex!". If the name prop were omitted in App.svelte, it would fall back to the default and render "Hello, World!".

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.