Search code examples
if-statementsveltecode-duplicationsvelte-3

Is there a better way in Svelte to include a conditional HTML element


I started to come across this problem a lot. I want to include an element around other elements if a boolean is true. In the example below I make two if statements, but if the code that I want to wrap is big this will make it unclear what is happening. Also, there will be duplicate code. Is there a better way to this solution?

<script>
   let boolean = true;
</script>

{#if}
   <img src="source" />
{/if}

{#if}
   <a href="/home">
      <img src="source" />
   </a>
{/if}

Solution

  • If this is something you find yourself doing often, you could make a ConditionalLink component out of it using slots.

    <!-- ConditionalLink.svelte -->
    <script>
        export let isWrapped = false;
        export let href;
    </script>
    
    {#if isWrapped}
    <a {href}>
        <slot/>
    </a>
    {:else}
    <slot/>
    {/if}
    

    It can be used like so:

    <script>
        import ConditionalLink from './ConditionalLink.svelte'; 
        let wrapLink = false;
    </script>
    
    <ConditionalLink isWrapped={wrapLink} href="#">
        I'm a link
    </ConditionalLink>
    
    <label><input type="checkbox" bind:checked={wrapLink}> wrap link</label>