Skip to content

Iconify for Svelte function: getIcon

This tutorial is part of Iconify for Svelte functions tutorial.

The function getIcon() retrieves icon data.

Usage

The function has the following parameter:

  • name, string. Icon name.

The function returns icon data in IconifyIcon format, null if icon is not available.

Examples

jsimport { getIcon } from '@iconify/svelte';

const data = getIcon('bi:check2-circle');
Result:
json{
   "body": "<g fill=\"currentColor\"><path fill-rule=\"evenodd\" d=\"M15.354 2.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L8 9.293l6.646-6.647a.5.5 0 0 1 .708 0z\"/><path fill-rule=\"evenodd\" d=\"M8 2.5A5.5 5.5 0 1 0 13.5 8a.5.5 0 0 1 1 0a6.5 6.5 0 1 1-3.25-5.63a.5.5 0 1 1-.5.865A5.472 5.472 0 0 0 8 2.5z\"/></g>",
   "left": 0,
   "top": 0,
   "width": 16,
   "height": 16,
   "rotate": 0,
   "vFlip": false,
   "hFlip": false
}

Another example:

jsimport { getIcon } from '@iconify/svelte';

const data = getIcon('cil:paper-plane');
Result:
json{
   "body": "<path fill=\"currentColor\" d=\"M474.444 19.857a20.336 20.336 0 0 0-21.592-2.781L33.737 213.8v38.066l176.037 70.414L322.69 496h38.074l120.3-455.4a20.342 20.342 0 0 0-6.62-20.743zM337.257 459.693L240.2 310.37l149.353-163.582l-23.631-21.576L215.4 290.069L70.257 232.012L443.7 56.72z\"/>",
   "left": 0,
   "top": 0,
   "width": 512,
   "height": 512,
   "rotate": 0,
   "vFlip": false,
   "hFlip": false
}

Example with bad icon name, returns null:

jsimport { getIcon } from '@iconify/svelte';

// null
const data = getIcon('no-such-icon');

Svelte component example

This example renders <slot /> while icon is being loaded, emulating behavior of React component. Due to bug in Svelte, third party components cannot use <slot />, so Svelte component behaves a bit different than other components.

svelte<script>
   import Icon, { getIcon, loadIcons } from '@iconify/svelte';
   import { onDestroy } from 'svelte';

   // Icon to render, string or object
   export let icon;

   // Icon data and cleanup function
   let data = null;
   let cleanup = null;
   let update = 0;

   $:
{
       // Mention dummy variable to trigger re-running this code from loadIcons() callback
       update;

       // Get icon data
       data = typeof icon === 'object' ? icon : getIcon(icon);

       // Cancel previous callback
       if (cleanup) {
           cleanup();
           cleanup = null;
       }

       // Load icon
       if (data === null) {
           cleanup = loadIcons([icon], () => {
               // Trigger re-running of code above
               update ++;
           });
       }
   }

   // Cleanup
   onDestroy(() => {
       if (cleanup) {
           cleanup();
       }
   })
</script>

{#if data}
   <Icon icon=
{data} />
{:else}
   <slot />
{/if}

Released under the Apache 2.0 License.