- I am using svelte 5 / sveltekit 2
- I have a simple example where I get data from an API that looks like this
const itemsFromAPI = [
{ id: 1, symbols: ['btc', 'eth'] },
{ id: 2, symbols: ['xrp', 'xmr'] }
];
- I want to render SVG icons corresponding to each symbol using this library
- Bear in mind, I am well aware they have a svelte version but it hasn't been updated in 5 years
- I wrote a simple +page.svelte file but it doesnt render
<script>
const itemsFromAPI = [
{ id: 1, symbols: ['btc', 'eth'] },
{ id: 2, symbols: ['xrp', 'xmr'] }
];
const handleIconChange = async (iconName) => {
return await import(`/node_modules/cryptocurrency-icons/svg/color/${iconName}.svg?inline`);
};
</script>
<h1>How to make dynamic crypto icons work here</h1>
{#each itemsFromAPI as item (item.id)}
<div>
<span>{item.id}</span>
{#each item.symbols as symbol (symbol)}
<span>{symbol}</span>
<span>{@html handleIconChange(symbol)}</span>
{/each}
</div>
{/each}
- Here is the link to the CODESANDBOX where you can see the problem first hand
- Any ideas how to make dynamically imported SVG icons work in sveltekit?
- I am using svelte 5 / sveltekit 2
- I have a simple example where I get data from an API that looks like this
const itemsFromAPI = [
{ id: 1, symbols: ['btc', 'eth'] },
{ id: 2, symbols: ['xrp', 'xmr'] }
];
- I want to render SVG icons corresponding to each symbol using this library
- Bear in mind, I am well aware they have a svelte version but it hasn't been updated in 5 years
- I wrote a simple +page.svelte file but it doesnt render
<script>
const itemsFromAPI = [
{ id: 1, symbols: ['btc', 'eth'] },
{ id: 2, symbols: ['xrp', 'xmr'] }
];
const handleIconChange = async (iconName) => {
return await import(`/node_modules/cryptocurrency-icons/svg/color/${iconName}.svg?inline`);
};
</script>
<h1>How to make dynamic crypto icons work here</h1>
{#each itemsFromAPI as item (item.id)}
<div>
<span>{item.id}</span>
{#each item.symbols as symbol (symbol)}
<span>{symbol}</span>
<span>{@html handleIconChange(symbol)}</span>
{/each}
</div>
{/each}
- Here is the link to the CODESANDBOX where you can see the problem first hand
- Any ideas how to make dynamically imported SVG icons work in sveltekit?
1 Answer
Reset to default 1The function returns a promise, to use that in the template you have to use an #await
block, also the query requires the raw
specifier, otherwise you get a URL when importing images (not sure if inline
does anything on dynamic imports, since it then would have to inline all possible files).
function handleIconChange(iconName) {
return import(`/node_modules/cryptocurrency-icons/svg/color/${iconName}.svg?raw`);
};
<!-- Content will be the default export, import() returns the entire module -->
{#await handleIconChange(symbol) then { default: icon }}
{@html icon}
{/await}