Skip to content

Check if #snippet is empty #17302

@hyunbinseo

Description

@hyunbinseo

Describe the problem

I would love to call showModal() only when there is a modal content:

<script lang="ts">
  import type { Snippet } from 'svelte';

  let { children }: { children?: Snippet | undefined } = $props();

  let dialog: HTMLDialogElement;

  // If children is non-empty, call `dialog.showModal()`
</script>

<dialog bind:this={dialog}>
  {@render children?.()}
</dialog>

But this does not work because children snippet is always a function with this if block:

function snippet2(node, args)

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

  let showContent = $state(false);
</script>

<Modal>
  {#if showContent}
    <h1>Hello, World!</h1>
  {/if}
</Modal>

<button type="button" onclick={() => (showContent = !showContent)}>
  Toggle
</button>

Describe the proposed solution

$effect(() => {
  // Something I can use here:
  if (children !== undefined) {
    dialog.showModal();
    return;
  }
  dialog.close();
});

For workaround, I am currently using explicit props:

{#snippet content()}
  <h1>Hello, World!</h1>
{/snippet}

<Modal children={showContent ? content : undefined}></Modal>

<button type="button" onclick={() => (showContent = !showContent)}>
  Toggle
</button>

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions