Search code examples
componentsparent-childsvelte

Pass Message from Parent to Child


I have a parent component with many child components repeated using an {#each} ... {/each} block, which receives updates from a webhook. I would like to propagate an update (which has an ID) into the child with the same ID. At first, I passed the update message as a prop, then checked if that prop had the same ID in the children. That felt inefficient since each child would have to process the message intended for only one child.

I then decided to use the module context feature, which allowed me to avoid checking in each component (demonstrated on the Svelte REPL here). I'm pretty satisfied with this solution, but I'm wondering if there is a better or more streamlined (or official!) way to do this since I imagine this is a pretty common scenario.


Solution

  • Using the module script for this is a bad idea. It means you can only have one instance of the component that uses said static context variables without causing conflicts.

    The proper approach is to use setContext in the parent and getContext in the child (or any descendant) to get access to a shared object.

    You can use stores in the context to preserve reactivity or use something like an EventTarget instance to pass events.