Working With SVGs in Svelte
- 2 minutes read
We can take advantage of some of Svelte’s built-in features to cleanly work with SVGs in powerful ways that might otherwise require additional lines of code.
Let’s start with the basics. If you had a file called ball.svg
, you could include it in your Svelte component like this:
<img src="/path/to/ball.svg" alt="An image of a red ball." />
Or, if you preferred, you could also store the <img>
tag attributes as variables:
<script>
const src = `/path/to/ball.svg`;
const alt = `An image of a red ball`;
</script>
<img {src} {alt} />
Anyway, let’s move on to some more interesting things we can do with our SVGs in Svelte.
Converting an SVG string to an SVG tag
You can convert an SVG string to markup using Svelte’s special HTML tag:
<script>
const svg = `<svg>...</svg>`;
</script>
{@html svg}
<!--
This will insert the "svg" variable into your component as HTML.
Example output:
<svg>
...
</svg>
-->
Converting an SVG file to an SVG tag
While there’s no simple way to include an SVG file as an SVG tag directly (without a plugin such as svelte-inline-svg), you can instead just inherit another Svelte component that only contains an inline SVG element.
For example, you could have an Icon.svelte
component that looks like this:
<!-- Icon.svelte -->
<svg>
...
</svg>
And then you could include that Icon.svelte
file from a parent component, such as this Component.svelte
:
<!-- Component.svelte -->
<script>
import Icon from '/path/to/Icon.svelte';
</script>
<Icon />
Conclusion
Anyway, I hope you found at least one of these snippets useful!
Thanks for reading.