DEV Community

myleftshoe
myleftshoe

Posted on

Svelte dialogs - the easy way

The simplest way to create a reusable dialog component using native HTML5 dialogs in svelte!

1) Create Dialog.svelte component:

<script>
    export let dialog
</script>
<dialog bind:this={dialog} on:close>
    <slot/>
</dialog>
Enter fullscreen mode Exit fullscreen mode

Here we export the ref to the native dialog which allows access to its methods by binding to dialog in the parent (below)

on:close simply forwards the native dialog's close event to the parent.

2) Use it in other component:

<script>
    import Dialog from './Dialog.svelte'
    let dialog
</script>

<button on:click={() => dialog.showModal()}>Open It!</button>

<Dialog bind:dialog on:close={() => console.log('closed')}>
    This is amazingly simple! (press esc to close)
</Dialog>
Enter fullscreen mode Exit fullscreen mode

See it working in the REPL!

;)

Top comments (2)

Collapse
 
darenw profile image
Daren Scot Wilson

If the popup has to show data and has a checkbox or slider to adjust a value, how to convey that data between the main app and the popup?

Collapse
 
myleftshoe profile image
myleftshoe

You would put the content between the Dialog tags, i.e. replace "This is amazingly simple! (press esc to close)" with your own markup. This content is passed into the . For communicating between the parent and child you could forward events to the parent and/or use slot props. Refer to the svelte docs:

learn.svelte.dev/tutorial/slot-props

Having said that, Svelte 5 is replacing slots with snippets. I haven't used it yet, but maybe you jump straight in with svelte 5 because it aims to simplify things.