'Passing action to a component optionally

I've learnt that it's possible to pass action to a component: https://stackoverflow.com/a/66142037/15943057. Now I wonder if it would be possible to pass one optionally.

I'm building a reusable <Wrapper> component that I want to be used with or without the action passed. If I try the answer linked above, but don't add action={myAction} (because I don't want any), I get two errors: (1) [HMR][Svelte] – "Unrecoverable error in : next update will trigger a full reload", (2) Unhandled Promise Rejection: TypeError: null is not an object (evaluating 'ctx[2].call'). To note, when I do add action={myAction}, everything works as expected.



Solution 1:[1]

You can just set a default that does nothing:

<script>
  export let action = () => {};
  export let actionParams = undefined;
</script>

<div use:action={actionParams} >
    <slot/>
</div>

REPL

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 H.B.