Fynn Budde

Using SVG in Svelte

January 26, 2024

2 min read

Introduction


If you’re trying to use an SVG in your Svelte project, it can be tricky to get it right. Here’s how I do it!


Let’s say we have an SVG like this:

<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g stroke-width="0"/>
  <g stroke-linecap="round" stroke-linejoin="round"/>
  <g >
    <path d="M7 8L3 11.6923L7 16M17 8L21 11.6923L17 16M14 4L10 20" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </g>
</svg>

Method 1


You can import the SVG as a raw HTML string using the ?raw suffix from VITE

<script>
  import MySVG from '$lib/icons/MySVG.svg?raw';
</script>

and to use it, write the following:

{@html MySVG}

The @html is a special tag from Svelte that does not escape characters like < and >. So in this example, the raw SVG string is used in the document.

The problem with this method is that we can’t style the SVG. To fix this, I use the next method.



Method 2


We start by creating a component called MySVG.svelte and insert the SVG code into it. Then we add a script section and add

let _class = '';
export { _class as class };

let _style = '';
export { _style as style };

Then include the variables as attributes like so:

<svg class={_class} style={_style}>...</svg>

then change all color codes in the SVG to currentColor so that the color from styles is used. In the end, the component should look like this:

<script>
  let _class = '';
  export { _class as class };

  let _style = '';
  export { _style as style };
</script>

<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g stroke-width="0"/>
  <g stroke-linecap="round" stroke-linejoin="round"/>
  <g >
    <path d="M7 8L3 11.6923L7 16M17 8L21 11.6923L17 16M14 4L10 20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </g>
</svg>

To use the SVG component, write this:

<script>
  import MySVG from '$lib/icons/MySVG.svelte';
</script>

<MySVG style="color: red; width: 50%" />

Result