flekschas/svelte-simple-modal

Usage in SvelteKit

jnsprnw opened this issue · 2 comments

Hey, thanks for maintaining this package!

I got it running in SvelteKit and thought I might save others some time by posting my solution here.

There is no need to import the package with onMount but use the browser variable instead:

routes/index.svelte

<script>
  import Modal from 'svelte-simple-modal';
  import { browser } from '$app/env';
</script>

{#if browser}
<Modal>
  <Content />
</Modal>
{/if}

Content.svelte and Surprise.svelte can remain as stated in the documentation.

But because I want Content.svelte to be rendered by SSR, I have a slightly modified version of your non-getContext suggestion:

routes/index.svelte

<script>
  import { writable } from 'svelte/store';
  import { browser } from '$app/env';
  import Modal from 'svelte-simple-modal';
  import Popup from '$lib/Modal/Popup.svelte';
  const modal = writable(null);

  function showModal() {
    modal.set(Popup);
  }
</script>

<Content on:showSurprise={showModal} />
{#if browser}
<Modal show={$modal}/>
{/if}

Content.svelte

<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();
  function showSurprise() {
    dispatch('showSurprise');
  }
</script>

<button on:click={() => showSurprise()}>

This alllows me to dispatch showSurprise without knowledge about the modal details.

All the best and thanks again.

This is neat! Thanks for sharing your setup.

Would you be interested setting up a PR to include this in the README? I am sure others would love to easily know about this setup as well. I am think it could probably be described after or before configuring the app bundler. What do you think?

We can figure out the details in the PR together. (The README is getting looong haha. Maybe I should factor out the API docs into it's own file)

I was out this weekend and just saw you updated the README already. Looks good and clear to me :)