HextaUI

Avatar: Loading

Initials show while the photo loads, then the photo fades in over them. A broken photo keeps the fallback. Pass delay to wait before showing initials, so fast photos never flash them.

ATBIGH
"use client"

import * as React from "react"

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"

export function AvatarLoading() {
  const [version, setVersion] = React.useState(0)
  const [loading, setLoading] = React.useState(false)
  const timer = React.useRef<number>(undefined)

  React.useEffect(() => () => window.clearTimeout(timer.current), [])

  const reload = () => {
    window.clearTimeout(timer.current)
    setLoading(true)
    timer.current = window.setTimeout(() => {
      setVersion((value) => value + 1)
      setLoading(false)
    }, 1200)
  }

  return (
    <div className="flex flex-wrap items-center gap-3">
      <Avatar size="xl">
        {loading ? null : (
          <AvatarImage src={`/preview/landscape.svg?v=${version}`} alt="" />
        )}
        <AvatarFallback>AT</AvatarFallback>
      </Avatar>
      <Avatar size="xl">
        <AvatarImage src="/preview/missing.png" alt="" />
        <AvatarFallback>BI</AvatarFallback>
      </Avatar>
      <Avatar size="xl">
        <AvatarImage src="/preview/landscape.svg" alt="" />
        <AvatarFallback delay={600}>GH</AvatarFallback>
      </Avatar>
      <Button variant="outline" size="sm" onClick={reload}>
        Load a new photo
      </Button>
    </div>
  )
}

This adds the example as components/examples/avatar/loading.tsx, together with the Avatar component and the HextaUI theme tokens it needs.

pnpm dlx shadcn@latest add https://hextaui.com/r/avatar-loading.json

To add only the component, follow the Avatar installation.

Props in this example

The Avatar props this example sets, from the API reference.

PropTypeDefault
sizeInherited from the group when omitted.
"xs" | "sm" | "default" | "lg" | "xl""default"
PropTypeDefault
src
string–
alt
string–
PropTypeDefault
delayMilliseconds to wait before showing it.
number0

Every prop is in the Avatar API reference.

See them all, with keyboard support and accessibility notes, on the Avatar page.