codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Passing Props Between Svelte Components

John Au-Yeung
codeburst
Published in
3 min readApr 28, 2020

--

Photo by Pineapple Supply Co. on Unsplash

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to pass data to child Svelte components via props.

Props

We can use the export keyword to create a variable that can be passed into a child within the child component itself.

For example, if App.svelte is the parent and Button.svelte is the child, then we can write the following to pass a value to the text prop of Button:

App.svelte :

<script>
import Button from "./Button.svelte";
</script>
<main>
<Button text='Toggle' />
</main>

Button.svelte :

<script>
export let text;
</script>
<button>
{text}
</button>

In the code above, we wrote:

export let text;

to indicate that Button takes text as a prop.

Then in App.svelte , we write:

<Button text='Toggle' />

to pass in the string 'Toggle' to Button . Since Button references text between the button tags, we see the word Toggle as the text for the button.

We can set default values of props by setting the value of our export expression as follows:

App.svelte :

<script>
import Button from "./Button.svelte";
</script>
<main>
<Button text='Toggle' />
<Button />
</main>

Button.svelte :

<script>
export let text = "Empty Button";
</script>
<button>
{text}
</button>

In the code above, we set text to 'Empty Button' in Button.svelte .

Therefore, when we have a Button without a text prop passed in, we’ll get that value as the text of the button.

Spread Props

We can use the spread operator to spread an object’s properties into multiple props.

For instance, if we want to pass in more than one prop, we can write the following:

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Responses (1)

Write a response