Skip to content

Iconify for Svelte function: iconExists

This tutorial is part of Iconify for Svelte functions tutorial.

The function iconExists() checks if icon data is available for rendering.

Usage

The function has the following parameter:

  • name, string. Icon name.

The function returns boolean value: true if icon is available, false if icon is not available.

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, { iconExists, loadIcons } from '@iconify/svelte';
   import { onDestroy } from 'svelte';

   // Icon to render, string
   export let icon;

   // Icon status and cleanup function
   let loaded = false;
   let cleanup = null;
   let update = 0;

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

       // Get icon data
       loaded = iconExists(icon);

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

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

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

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

This example uses iconExists() to show function, but for this purpose it is better to use getIcon(). See getIcon() documentation for better example.

Released under the Apache 2.0 License.