MaxCore
MaxCore

Reputation: 2728

Svelte: transferring props between parent and child

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

Upvotes: 0

Views: 869

Answers (1)

joshnuss
joshnuss

Reputation: 2047

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/>

Upvotes: 1

Related Questions