svgsveltesveltekitsvelte-5

Dynamically imported SVG icons not working


    const itemsFromAPI = [
        { id: 1, symbols: ['btc', 'eth'] },
        { id: 2, symbols: ['xrp', 'xmr'] }
    ];
<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}


Solution

  • The 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}