1
votes

I am new to svelte, I would like to know if there is way to pass data from parent to nested child component and execute function on child component.

Below is the code for App.svelte

<script>
  import Outer from "./Outer.svelte";
  let dataMap = {};
  function handleIncommingMessage(message) {
    dataMap[message.key] = message;
  }
</script>
<Outer {dataMap} />

This is the Outer Component Outer.svelte

<script>
    import Inner from './Inner.svelte';
    export let dataMap;
</script>

<Inner {dataMap}/>

This is the inner Component Inner.svelte

<script>
    export let dataMap;
    function executeChildFunction() {
        //Process received dataMap
    }
</script>

<div>
<!-- Display processed dataMap -->
</div>

I want to run the executeChildFunction in the Inner.svelte. I know to createEventDispatcher in Inner.svelte and execute a function in App.svelte. But I would like to know if the other way is possible, createEventDispatcher in Parent and execute function in child. Kindly let me know. Thank You.

1

1 Answers

3
votes

Make it reactive:

<script>
    export let dataMap;

    function executeChildFunction(dataMap) {
        //Process received dataMap
    }

    $: executeChildFunction(dataMap);
</script>

<div>
    <!-- Display processed dataMap -->
</div>