Props

So far, we have only dealt with internal state, that is, these values can only be accessed in a given component.

In any real application, you need to pass data from one component to its children. To do this, we need to declare properties, often referred to simply as “props”. In Svelte, we use the export keyword to do this. Edit nested.svelte component:

<script>
	export let answer;
</script>

<p>The answer is {answer}</p>
Copy the code

Like $:, it might feel a little weird at first. Exporting in JavaScript modules usually doesn’t work this way! Now let nature take its course — it will soon become second nature.

App. Svelte file:

<script>
	import Nested from './Nested.svelte';
</script>

<Nested answer={42} />
Copy the code

Props to the default value

In Neted.svelte, we can easily specify default values for items:

<script>
	export let answer = 'a mystery';
</script>
Copy the code

If we now add a second component with no value passed, it will use the default value:

<Nested answer={42} />
<Nested/>
Copy the code

Output:

The answer is 42
The answer is a mystery
Copy the code

Props by value

If you have a property object, you might pass values like this:

<script>
	import Info from './Info.svelte';

	const pkg = {
		name: 'svelte'.version: 3.speed: 'blazing'.website: 'https://svelte.dev'
	};
</script>

<Info name={pkg.name} version={pkg.version} speed={pkg.speed} website={pkg.website}/>
Copy the code

But in Svelte, you can go like this:

<script>
	import Info from './Info.svelte';

	const pkg = {
		name: 'svelte'.version: 3.speed: 'blazing'.website: 'https://svelte.dev'
	};
</script>

<Info {. pkg} / >
Copy the code

Info. Svelte code:

<script>
	export let name;
	export let version;
	export let speed;
	export let website;
</script>

<p>
	The <code>{name}</code> package is {speed} fast.
	Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a>
	and <a href={website}>learn more here</a>
</p>
Copy the code

Of course, if you need to reference all the keys passed to the component, including those not declared through export, you can access $props directly. Svelte is generally not recommended because it is difficult to optimize, but can be very useful in rare cases.

To try out the above functionality for yourself, check out the Sevlte tutorial on the Sevlte website: Props