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 (1)

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?