Svelte: transferring props between parent and child

Asked By: Anonymous

I’ve wrote simple Modal component with two slots named button and content:

<script>
    let opened = false;

    function open() {
        opened = true;
    }
</script>

<slot name="button" opened={opened} open={open}/>

{#if opened}
    <slot name="content"/>
{/if}

Also, opened and open-method are passed to parent component via <slot name="button"

In App.svelte:

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

<Modal let:opened let:open>
    <button slot="button" on:click={open} class:opened>Open</button>
    <div slot="content">Content</div>
</Modal>

So, there are two questions:

1) It looks a little bit weird that props can be passed to parent just through any random slot.

Is it a good practice to do it like this?:

<slot opened={opened} open={open}/>

<slot name="button"/>

{#if opened}
    <slot name="content"/>
{/if}

2) <div slot="content">Content</div> passed with its <div>. Could I pass only Content without <div> or can Content be unwrapped somehow?

Thx


Solution

Answered By: Anonymous

1) Yes it’s totally fine.
Alternative is to use data-binding or events to send info to a parent.

2) You can have a default slot, and it wouldn’t need a wrapping element. Example:

<!-- Modal.svelte -->

<!-- named slot -->
<slot name="button"/>

<!-- unnamed/default slot -->
<slot/>
<!-- usage -->
<Modal>
  <button slot="button"/>
  I'm unwrapped in the default slot! 
<slot/>

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno