I've a experimented with a few different ways of handling SVG icons in Svelte. Here's a brief thread about the workflow that I'm enjoying lately.
↓↓↓
I looked at using <img> tags, directly inlining the SVG, and passing the SVG as a component. Of these three, the last is the one that seems to result in the most maintainable code
I originally used a <slot>, and passed the icon component into it. This works, but not when generating the components dynamically:
What I've come to prefer is passing the icon component as a prop, and using <svelte:component> to render it, which works in both static and dynamic situations.
I start by optimizing the SVG file directly into a Svelte component using svgo:
I then make any edits, such as changing hard-coded colors to `currentColor` so the icon can inherit its color. It's also important to hard-code a starting width and height (a viewbox alone won't work). If the `xmlns` attribute is not present, you may need to add this as well:
Then we display the icon with <svelte:component>, rather than <slot>. When we use that component, we just import the relevant icon and pass it as a prop instead of a tag:
I really like this pattern. It allows you to dynamically generate components that include SVGs, for example by using an {#each} block on an array of objects. Interested in other approaches if anyone wants to share them.
• • •
Missing some Tweet in this thread? You can try to
force a refresh