chovy
chovy

Reputation: 75656

How do I pass an optional event handler to a svelte component?

I have a re-usable component Tags.svelte and I want to optionally pass a click handler:

<Tags {tags} {clickHandler} />

I can make the parameter optional but I don't know how to attach it to my tag <button> item in the component if its optional

Normally I would do:

<button on:click|preventDefault={clickHandler}>{tag}</button>

but how do I make this optional?

Upvotes: 1

Views: 2190

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9939

You could use a simple {#if} block to branch out what is rendered:

<script>
  export let tags
  export let clickHandler    # undefined and will evaluate to false if not set, will evaluate to true if set
</script>

{#each tags as tag}
  {#if clickHandler}
    <button on:click|preventDefault={clickHandler}>{tag}</button>
  {:else}
    <span>{tag}</span>
  {/if}
{/each}

Upvotes: 4

Related Questions