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