Mathieu Arthur
Mathieu Arthur

Reputation: 31

How to use modal in svelte

Hello I have an error when I try to do some svelte modal.

This is the code for the App.svelte :

<script>
    import Podcast from "./components/Podcast.svelte";
    import Modal from 'svelte-simple-modal';
</script>

<style>

</style>

<main>
    <Modal>
        <Podcast color={"red"} title={"red"} />
    </Modal>
    <Podcast color={"green"} title={"green"} />
    <Podcast color={"blue"} title={"blue"} />
    <Podcast color={"purple"} title={"purple"} />
    <Podcast color={"yellow"} title={"yellow"} />
    <Podcast color={"brown"} title={"brown"} />
    <Podcast color={"orange"} title={"orange"} />
</main>

Here is my podcast component where I want to handle the click :

<script>
    import { getContext } from 'svelte';
    import ModalContent from './ModalContent.svelte';

    export let title;
    export let color;
    
    const { open } = getContext('simple-modal');
  
    const showModal= () => {
      open(ModalContent);
    };
</script>

<style>
    section
    {
        width: auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>

<section on:click={showModal} style="background-color: {color}">
      The title is : &nbsp;
    <b> 
        {title} 
    </b>
</section>

And here the content of my modal (just for test purpose rn) :

<script>
    // your script goes here
</script>

<style>
    /* your styles go here */
</style>

test test

and I have this error :

Uncaught TypeError: Cannot destructure property 'open' of 'getContext(...)' as it is undefined.

Any idea ?

Upvotes: 0

Views: 1854

Answers (1)

Geoff Rich
Geoff Rich

Reputation: 5472

Context is only available to children of the component that set the context (tutorial chapter). Because of this, <Modal> needs to wrap your entire application.

<main>
    <Modal>
        <Podcast color={"green"} title={"green"} />
        <Podcast color={"blue"} title={"blue"} />
        <Podcast color={"purple"} title={"purple"} />
        <Podcast color={"yellow"} title={"yellow"} />
        <Podcast color={"brown"} title={"brown"} />
        <Podcast color={"orange"} title={"orange"} />
    </Modal>
</main>

The exception you were seeing was thrown by <Podcast> components that were not children of <Modal>, so the simple-modal context was not set.

Upvotes: 2

Related Questions