Home > Back-end >  Correct way of changing svg image in svelte
Correct way of changing svg image in svelte

Time:08-10

In svelte, I have the option of switching between two images, or using css to change the color of the svg image. Which is "better/ best practice"? (also we use tailwind css).

    <div class='w-2 h-2'>
     {#if condition}
      <Image1/>  <--white image
     {:else}
      <Image2/>  <--red image
     {/if}
    </div>

OR If the default image is white, this passes red to it. The color variable would be text-red or text-white based on some condition.

    <div class='w-2 h-2 ${color}'> 
      <Image1/>
    </div>

CodePudding user response:

Svelte's reactivity can take over colour conditions via CSS. We can avoid the if condition.

App.svelte

<script>
import Icon from "./Icon.svelte"

let stroke = "green";

function changeStroke(){
    stroke = "red"
}

</script>

<Icon {stroke}/>

<button on:click={changeStroke}>Change</button>

Icon.svelte

<script>
export let stroke = 'white';
</script>

<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" {stroke} stroke-width="2">
  <!-- Big SVG -->
</svg>

See this example REPL

  • Related