Skip to content

Dynamic icon names

Named imports need the icon name when you write the code. When it only comes at runtime, e.g. from an API response like { "icon": "lucide:trash-2" }, load the icon by its name with the dumped loaders map:

import { createIconElement, loadIcon } from '@silarhi/ux-icons-js'
import { loaders } from '../var/icons/loaders.js'
const data = await (await fetch('/api/status')).json()
const icon = await loadIcon(loaders, data.icon) // null for an unknown name
if (icon) {
badge.append(createIconElement(icon, { class: 'text-success' }))
}

Try it: type a name, as if it came from an API. Each icon is downloaded on its first use only, open the network tab of your browser to see it.

Loaded: none yet

var/icons/loaders.js maps every dumped name, aliases included, to the module of that icon alone:

export const loaders = {
'lucide:trash-2': () => import('./icons/lucide--trash-2.js'),
// …
}

Your bundler splits each icon into its own chunk: importing loaders downloads none of them, and loadIcon() downloads only the requested one. Static imports from index.js are not affected, they stay in your bundle and tree-shaken; and an app that only uses UXIcon does not bundle the loading code of UXLazyIcon.

loadIcon(loaders: UXIconLoaders, name: string | null | undefined): Promise<UXIconData | null>
  • Resolves to null for null, undefined, or a name the dump does not know.
  • Loads each icon once: concurrent and later calls share the same result. getLoadedIcon(loaders, name) returns an icon already loaded, synchronously.
  • Rejects if the module fails to load (e.g. a network error); the next call tries again.

preloadIcons() loads several icons at once, e.g. the icons of a menu before it opens, so that they render without a fallback. It resolves to the icons in the same order, null for an unknown name:

import { hasIcon, preloadIcons } from '@silarhi/ux-icons-js'
await preloadIcons(
loaders,
items.map((item) => item.icon)
)

hasIcon() tells whether the dump knows a name, without loading it, e.g. to validate a name from a CMS:

if (!hasIcon(loaders, block.icon)) {
console.warn(`Unknown icon "${block.icon}"`)
}

UXLazyIcon takes the name and the loaders, and the other props of UXIcon. It renders the fallback while the icon loads, or for an unknown name:

import { UXLazyIcon } from '@silarhi/ux-icons-js/react'
import { loaders } from '../var/icons/loaders.js'
const badge = <UXLazyIcon name={status.icon} loaders={loaders} fallback={<span className="placeholder" />} />

With Preact, import it from @silarhi/ux-icons-js/preact; the props are the same, with Preact’s class.

<UXLazyIcon :name="status.icon" :loaders="loaders" class="text-success">
<template #fallback><span class="placeholder" /></template>
</UXLazyIcon>

An icon loaded earlier renders at once, without the fallback, also during a server-side render.

To render the icon yourself, useIcon() returns it once loaded, and null while it loads, for an unknown name, or if it fails to load. It is a hook in React and Preact:

import { UXIcon, useIcon } from '@silarhi/ux-icons-js/react'
function StatusBadge({ status }) {
const icon = useIcon(loaders, status.icon)
return <span className="badge">{icon ? <UXIcon icon={icon} /> : status.label}</span>
}

and a composable in Vue, which takes the name as a value, a ref or a getter, and returns a ref:

<script setup>
import { UXIcon, useIcon } from '@silarhi/ux-icons-js/vue'
import { loaders } from '../var/icons/loaders.js'
const props = defineProps(['status'])
const icon = useIcon(loaders, () => props.status.icon)
</script>
<template>
<UXIcon v-if="icon" :icon="icon" />
</template>

The <ux-icon> element renders an icon by its name in plain HTML: Twig templates, Turbo Streams, HTML built by a Stimulus controller.

The dumped loaders.d.ts exports the union of the dumped names, to type your API responses:

import type { IconName } from '../var/icons/loaders.js'
interface Status {
label: string
icon: IconName // 'lucide:trash-2' | 'user' | …
}

The names are typed from the loaders: your editor suggests the dumped names for loadIcon(), useIcon() and the name of UXLazyIcon, and loadIcon() resolves to a UXIconData<IconName>. Any other string is still accepted, as a name from an API is only known at runtime. hasIcon() narrows a string to IconName:

const name: string = data.icon
if (hasIcon(loaders, name)) {
// name: IconName
}

This needs TypeScript 5.4 or later (NoInfer).

Like the named exports, the loaders only know the dumped, local icons. ux:icons:lock cannot guess the names an API returns: download them first with ux:icons:import (see remote icons), or keep them in your icon directory.

An application that never loads an icon by its name can skip loaders.js and the icon modules with dump_loaders: false.