DEV Community

Nguyen Dang Khoa
Nguyen Dang Khoa

Posted on

How to send data from child component to parent component through <slot> in Svelte

I was using SvelteKit version 1.0.0-next.483 when I wrote this. Things might change due to Svelte being young.

The problem

So I'm used to throwing data from a parent container to a child component in Svelte but what if I wanted to do the opposite?

Here's the problem I had in my project:

This is the child component called SectionTitle.svelte

<div class="section-title">
    <div class="section-icon">
        <slot />
    </div>
    <h2 class="large-text">{sectionTitle}</h2>
</div>
Enter fullscreen mode Exit fullscreen mode

This is the parent that uses SectionTitle.svelte

<SectionTitle sectionTitle="Book" let:sectionIcon>
    <Books color="red" width="32" height="32" />
</SectionTitle>

Enter fullscreen mode Exit fullscreen mode

So my SectionTitle component needs a <slot> so that when I import it I can throw in an icon component called <Books>. It works fine... until I realized every single icons I put in SectionTitle need those properties: color="red" width="32" height="32"

My solution

I need to somehow let my child has its own default props value to release its parents from pain

SectionTitle.svelte

<script>
    export let sectionTitle = '';

    let sectionIcon = {
        color: 'var(--primary-600)',
        height: 32,
        width: 32,
    };
</script>

<div class="section-title">
    <div class="section-icon">
        <slot sectionIcon={sectionIcon} />
    </div>
    <h2 class="large-text">{sectionTitle}</h2>
</div>

Enter fullscreen mode Exit fullscreen mode

Then I import and used SectionTitle.svelte like this:

<SectionTitle sectionTitle="UI + UX" let:sectionIcon>
    <FigmaLogo {...sectionIcon} />
</SectionTitle>

<SectionTitle sectionTitle="Book" let:sectionIcon>
    <Books {...sectionIcon} />
</SectionTitle>
Enter fullscreen mode Exit fullscreen mode

So now I have some default values for my icons, before I even know what icon components to put inside the <slot>

I'm still learning Svelte. If you have any suggestions, please comment down below.

Top comments (0)