---
title: Icon for Astro
description: "Astro icon rendering for Lucide symbols and Simple Icons brand marks."
seo:
    title: Icon for Astro | Shadcn & Tailwind CSS
related:
    - /components/button
    - /components/logo
sidebar:
    label: "Icon"
---

The `Icon` component resolves [Lucide](https://lucide.dev) and [Simple Icons](https://simpleicons.org) icons.

- Use the `Icon` component when an icon name comes from content,
  frontmatter, or project configuration.
- Import `@lucide/astro` or `simple-icons` components directly when the
  icon is code-owned UI.

Pass a kebab-case slug, for example `map-pin`. Prefix a name with `lucide:` or
`simple:` to choose one set, for example `lucide:github` or `simple:github`.
Icons are decorative by default. Pass an `aria-label` when the icon carries
meaning.

**How a name resolves**

1. **Read name or href**

    A set `name` is the slug. With no name, a known `href` supplies the slug.

2. **Choose the search order**

    A name searches Lucide, then Simple Icons. A link searches Simple Icons, then Lucide.

3. **Honor a prefix**

    `lucide:` or `simple:` searches only that set.

4. **Render the match**

    The first matching icon renders. An unknown name renders no mark.

```astro
---
import { Icon } from "@/components/ui/icon"
---

<Icon name="rocket" />
<Icon name="github" />
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/icon
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add simple-icons
```

#### src/components/ui/icon/icon.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { resolveIcon } from "./resolve-icon.ts"
import type { IconProps } from "./types.ts"
import { cn } from "cn"

type Props = IconProps & Omit<HTMLAttributes<"svg">, "name" | "href">

const { name, href, class: className, ...props } = Astro.props

/** Loaded Lucide component or Simple Icons path data. */
const resolved = await resolveIcon({ name, href })
const LucideIcon = resolved?.source === "lucide" ? resolved.Icon : undefined
const simpleIcon = resolved?.source === "simple" ? resolved.icon : undefined

const isLabelled =
  "aria-label" in props || "aria-labelledby" in props || "role" in props

const iconClass = cn("size-[1em] text-base", className)

const requested = name ?? href
if (requested != null && requested !== "" && !LucideIcon && !simpleIcon) {
  Astro.logger?.warn(
    `Icon "${requested}" was not found in Lucide or Simple Icons`,
  )
}
---

{LucideIcon && (
  <LucideIcon
    class={iconClass}
    aria-hidden={isLabelled ? undefined : "true"}
    {...props}
  />
)}
{simpleIcon && (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    role="img"
    height={24}
    width={24}
    fill="currentColor"
    class={iconClass}
    aria-hidden={isLabelled ? undefined : "true"}
    {...props}
  >
    <title>{simpleIcon.title}</title>
    <path d={simpleIcon.path} />
  </svg>
)}
```

#### src/components/ui/icon/icon-frame.astro

```astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import { iconFrameVariants, type IconFrameVariants } from "./icon-variants"

import { cn } from "cn"

type Props<T extends HTMLTag = "span"> = Polymorphic<{ as: T }> &
  HTMLAttributes<T> &
  IconFrameVariants

const {
  as: Tag = "span",
  class: className,
  size,
  variant,
  ...props
} = Astro.props
---

<Tag class={cn(iconFrameVariants({ size, variant }), className)} {...props}>
  <slot />
</Tag>
```

#### src/components/ui/icon/icon-variants.ts

```ts
import { cva, type VariantProps } from 'class-variance-authority'

export const iconFrameVariants = cva(
    "flex shrink-0 items-center justify-center rounded-lg ring-1 inset-shadow-[0_1px_--theme(--color-white/65%)] ring-inset dark:inset-shadow-[0_1px_--theme(--color-white/10%)] [&>svg:not-[class*='size-']]:size-5",
    {
        variants: {
            size: {
                default: 'size-10',
                sm: "size-8 [&>svg:not-[class*='size-']]:size-4",
                lg: "size-12 [&>svg:not-[class*='size-']]:size-6",
            },
            variant: {
                default: 'bg-primary/12 text-primary ring-primary/20',
                glass: 'bg-white/12 text-white ring-white/20 backdrop-blur-md',
                outline: 'text-foreground ring-foreground/20 bg-transparent',
            },
        },
        defaultVariants: {
            size: 'default',
            variant: 'default',
        },
    },
)

export type IconFrameVariants = VariantProps<typeof iconFrameVariants>
```

#### src/components/ui/icon/lucide-icon.ts

```ts
import type { HTMLAttributes } from 'astro/types'

/** Astro renders each Lucide icon module as a component. */
export type LucideIconComponent = (props: HTMLAttributes<'svg'>) => unknown

/**
 * Lazy loaders for Lucide icon modules.
 * The server build includes all matching modules for content name lookup.
 * The slug is the kebab-case name on lucide.dev, for example `map-pin`.
 *
 * The parent node_modules path is used to support a monorepo structure. Remove it if the `@lucide/astro` package is installed in the app root.
 */
const lucideIconModules = import.meta.glob<{ default: LucideIconComponent }>(
    [
        '/node_modules/@lucide/astro/src/icons/*.ts',
        '/../node_modules/@lucide/astro/src/icons/*.ts',
        '!**/icons/index.ts',
    ],
    { exhaustive: true },
)

/** Index loaders by slug without loading the icon modules. */
const lucideIconLoaders = new Map<string, (typeof lucideIconModules)[string]>()
for (const [path, load] of Object.entries(lucideIconModules)) {
    const slug = path.slice(path.lastIndexOf('/') + 1, -3)
    // Keep the first match when both package paths contain the same slug.
    if (!lucideIconLoaders.has(slug)) lucideIconLoaders.set(slug, load)
}

/** True when Lucide ships a module for this slug. */
export function hasLucideIcon(name: string): boolean {
    return lucideIconLoaders.has(name)
}

/** Load one Lucide component. Returns undefined when the slug is unknown. */
export async function loadLucideIcon(
    name: string,
): Promise<LucideIconComponent | undefined> {
    const load = lucideIconLoaders.get(name)
    if (!load) return undefined
    const module = await load()
    return module.default
}
```

#### src/components/ui/icon/resolve-icon.ts

```ts
import type { SimpleIcon } from 'simple-icons'

import type { LucideIconComponent } from './lucide-icon.ts'
import type { IconProps } from './types.ts'

export type IconSource = 'lucide' | 'simple'

/** A loaded icon component and the set it came from. */
export type ResolvedIcon =
    | {
          source: 'lucide'
          /** Lucide Astro component for the resolved slug. */
          Icon: LucideIconComponent
      }
    | {
          source: 'simple'
          /** Simple Icons path data for the resolved slug. */
          icon: SimpleIcon
      }

type SelectedIcon = {
    source: IconSource
    /** Icon slug, for example `menu` or `github`. */
    name: string
}

/**
 * Link text that selects an icon when the caller passes `href`.
 * A slug such as `x` exists in Lucide and in Simple Icons.
 * The link selects the brand mark. `phone`, `mail`, and `map-pin`
 * are Lucide icons and are used when Simple Icons has no match.
 */
export const hrefIconMap = {
    'x.com': 'x',
    twitter: 'twitter',
    facebook: 'facebook',
    instagram: 'instagram',
    pinterest: 'pinterest',
    youtube: 'youtube',
    tiktok: 'tiktok',
    snapchat: 'snapchat',
    reddit: 'reddit',
    tumblr: 'tumblr',
    'wa.me': 'whatsapp',
    telegram: 'telegram',
    // telegram short link
    't.me': 'telegram',
    discord: 'discord',
    vimeo: 'vimeo',
    flickr: 'flickr',
    yelp: 'yelp',
    spotify: 'spotify',
    behance: 'behance',
    dribbble: 'dribbble',
    soundcloud: 'soundcloud',
    github: 'github',
    twitch: 'twitch',
    'tel:': 'phone',
    'mailto:': 'mail',
    'maps.app.goo.gl': 'google-maps',
    // google business profile short link
    'g.page': 'google',
    linkedin: 'linkedin',
    // youtube short link
    'youtu.be': 'youtube',
    'trustpilot.com': 'trustpilot',
} as const

/**
 * Choose a Lucide or Simple Icons slug for a content name or a link.
 * A plain name tries Lucide first. A link tries Simple Icons first.
 * Prefix a name with `lucide:` or `simple:` to choose the set.
 */
export async function selectIcon(
    input: Pick<IconProps, 'name' | 'href'>,
    hasIcon: (source: IconSource, name: string) => boolean | Promise<boolean>,
): Promise<SelectedIcon | undefined> {
    let key =
        input.name != null && input.name !== '' ? String(input.name) : undefined
    let order = ['lucide', 'simple'] satisfies IconSource[]

    // if no name is provided, try to resolve from the href
    if (!key && input.href) {
        const hrefText = input.href.toString()
        const hrefKey = (
            Object.keys(hrefIconMap) as (keyof typeof hrefIconMap)[]
        ).find((candidate) => hrefText.includes(candidate))
        if (hrefKey) {
            key = hrefIconMap[hrefKey]
            order = ['simple', 'lucide']
        }
    }

    if (!key) return undefined
    // `x.com` is a link fragment, not a Lucide slug.
    if (key === 'x.com') key = 'simple:x'

    const [prefix, icon] = (
        key.includes(':') ? key.split(':') : [undefined, key]
    ) as [string | undefined, string | undefined]
    if (prefix === 'lucide' || prefix === 'simple') order = [prefix]
    if (!icon) return undefined

    for (const source of order) {
        if (await hasIcon(source, icon)) return { source, name: icon }
    }

    return undefined
}

/**
 * Load a Lucide component or Simple Icons data for a content name or a link.
 * Returns undefined when the name and href do not match an icon.
 */
export async function resolveIcon(
    input: Pick<IconProps, 'name' | 'href'>,
): Promise<ResolvedIcon | undefined> {
    // Import each set only when selection reaches it.
    const selected = await selectIcon(input, async (source, iconName) => {
        if (source === 'lucide') {
            const { hasLucideIcon } = await import('./lucide-icon.ts')
            return hasLucideIcon(iconName)
        }
        const { hasSimpleIcon } = await import('./simple-icon.ts')
        return hasSimpleIcon(iconName)
    })
    if (!selected) return undefined

    if (selected.source === 'lucide') {
        const { loadLucideIcon } = await import('./lucide-icon.ts')
        const Icon = await loadLucideIcon(selected.name)
        return Icon ? { source: 'lucide', Icon } : undefined
    }

    const { loadSimpleIcon } = await import('./simple-icon.ts')
    const icon = await loadSimpleIcon(selected.name)
    return icon ? { source: 'simple', icon } : undefined
}
```

#### src/components/ui/icon/simple-icon.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { loadSimpleIcon } from "./simple-icon.ts"

type Props = Omit<HTMLAttributes<"svg">, "name"> & {
  /** Simple Icons slug, for example `github` or `x`. */
  name: string
}

const {
  name,
  class: className = "size-[1em] text-base",
  ...props
} = Astro.props

const icon = loadSimpleIcon(name)

if (!icon) {
  console.warn(`Simple Icons icon ${name} not found`)
}
---

{icon && (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    role="img"
    height={24}
    width={24}
    fill="currentColor"
    class={className}
    {...props}
  >
    <title>{icon.title}</title>
    <path d={icon.path} />
  </svg>
)}
```

#### src/components/ui/icon/simple-icon.ts

```ts
import * as icons from 'simple-icons'

/**
 * Read icon data on the server and render paths inline.
 * An SVG glob makes Astro emit every matching SVG as a public asset.
 * Static builds discard this data after page rendering. Server builds retain it.
 */
const simpleIcons = new Map(
    Object.values(icons).map((icon) => [icon.slug, icon]),
)

/** True when Simple Icons has this slug. */
export function hasSimpleIcon(name: string) {
    return simpleIcons.has(name)
}

/** Load icon data. Returns undefined when the slug is unknown. */
export function loadSimpleIcon(name: string) {
    return simpleIcons.get(name)
}
```

#### src/components/ui/icon/types.ts

```ts
import type { HTMLAttributes } from 'astro/types'

// not adding the lucide icon names to this as it would cause ~2000 icon names to be listed in the docs

export type IconName = `lucide:${string}` | `simple:${string}`

export type IconProps = {
    /** Link used to select a brand icon when `name` is omitted. */
    href?: HTMLAttributes<'a'>['href']
    /**
     * Icon slug from lucide.dev or Simple Icons. Lucide is tried first.
     * Use `simple:` or `lucide:` when the slug exists in both sets.
     */
    name?: IconName | (string & {})
}
```

#### src/components/ui/icon/index.ts

```ts
export { default as Icon } from './icon.astro'
export { default as IconFrame } from './icon-frame.astro'
export * from './types.ts'
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Direct imports

```astro
---
import Check from "@lucide/astro/icons/check"
import Heart from "@lucide/astro/icons/heart"
import MessageCircle from "@lucide/astro/icons/message-circle"
import Star from "@lucide/astro/icons/star"
import Trash2 from "@lucide/astro/icons/trash"
import Github from "simple-icons/icons/github.svg"
---

<Heart />
<Star />
<Check />
<Trash2 />
<MessageCircle />
<Github fill="currentColor" />
```

## Usage

For content-owned icons, pass plain names to `Icon`:

```astro
<Icon name={feature.icon} />
```

For UI icons that are fixed in code:

```ts
import Heart from "@lucide/astro/icons/heart"
```

```astro
<Heart />
```

For brand icons:

```ts
import Github from "simple-icons/icons/github.svg"
```

```astro
<Github fill="currentColor" />
```

## Example

Add `data-icon` to a Lucide icon used in a control. The control can then apply its own icon alignment and size rules.

```astro
---
import ArrowRight from "@lucide/astro/icons/arrow-right"

import { Button } from "@/components/ui/button"
---

<Button>
  Continue
  <ArrowRight data-icon="inline-end" />
</Button>
```

## Notes

- Use plain icon names in content, frontmatter, or project configuration.
- Render content-owned icon names through `Icon`.
- Import icon components directly for fixed code-owned UI icons.
- Prefer `@lucide/astro` for interface icons and `simple-icons` for brand
  marks when importing directly.
- Named Simple Icons use path data on the server and render inline SVG.
  Static builds include the rendered icons without copying the full SVG set.
  Server builds keep the icon data for lookup at request time.

## API Reference

Read the [installed source](/r/icon.json) for the complete prop types.

## When to use Icon

Use Icon when content data supplies an icon name or brand reference. Import Lucide directly for fixed interface icons when that makes the source clearer. Keep icon use consistent within one action row.

## Keyboard and behavior

Decorative icons should stay hidden from assistive technology. Name the button or link that contains an icon-only action. An unknown icon name renders no mark, so verify values that come from a CMS.

## Theme and layout

Match icon size to the text and use current text color for interface symbols. Brand artwork can require its own contrast treatment in dark mode; do not rely on a low-contrast logo alone to identify a link.
