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>
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>
See it working in the REPL!
;)
Top comments (2)
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?
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.