아바타(Avatar)
사용자나 개체를 이미지로 보여주고, 이미지가 없거나 로딩에 실패할 때 대체 텍스트를 표시하는 컴포넌트예요. 프로필 사진처럼 상태를 우아하게 처리해야 하는 곳에 딱 맞아요.
출처: 문서
본문
<script lang="ts">
import { Avatar } from "bits-ui";
</script>
<Avatar.Root
delayMs={200}
class="data-[status=loaded]:border-foreground bg-muted text-muted-foreground h-12 w-12 rounded-full border text-[17px] font-medium uppercase data-[status=loading]:border-transparent"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
개요(Overview)
Avatar 컴포넌트는 앱 곳곳에서 사용자나 개체 이미지를 일관된 방식으로 보여주도록 도와줘요. 이미지 로딩 상태를 자연스럽게 처리하고, 이미지 로드에 실패했을 때는 대체 콘텐츠를 제공해서 UI가 흔들리지 않고 견고하게 유지되게 해요.
기능(Features)
- 스마트 이미지 로딩: 이미지 로딩 상태를 자동으로 감지하고 처리해요.
- 대체 시스템(Fallback System): 이미지를 사용할 수 없거나 로딩이 느릴 때 대체 요소를 보여줘요.
- 복합 구조(Compound Structure): 조합하고 커스터마이징할 수 있는 유연한 기본 요소들로 이루어져 있어요.
- 커스터마이징: 이미지가 반드시 로드될 거라고 확신한다면, 로딩 검사를 생략하고 바로 보여주도록 선택할 수 있어요.
구조(Architecture)
Avatar 컴포넌트는 세 가지 핵심 부분으로 이루어진 복합 컴포넌트 패턴을 따라요.
- Avatar.Root: 이미지와 대체 요소의 상태를 관리하는 컨테이너예요.
- Avatar.Image: 사용자나 개체의 이미지를 표시해요.
- Avatar.Fallback: 이미지가 로딩 중이거나 로드에 실패했을 때 보여주는 요소예요.
빠른 시작(Quick Start)
Avatar 컴포넌트를 시작하려면 Avatar.Root, Avatar.Image, Avatar.Fallback 기본 요소를 활용해 아주 간단한 아바타를 만들 수 있어요.
<script lang="ts">
import { Avatar } from "bits-ui";
</script>
<Avatar.Root>
<Avatar.Image
src="https://github.com/huntabyte.png"
alt="Huntabyte's avatar"
/>
<Avatar.Fallback>HB</Avatar.Fallback>
</Avatar.Root>
재사용 컴포넌트(Reusable Components)
앱 전반에 걸쳐 일관된 스타일과 동작을 유지하려면 나만의 재사용 Avatar 컴포넌트를 만들어 둘 수 있어요.
UserAvatar.svelte
<script lang="ts">
import { Avatar, type WithoutChildrenOrChild } from "bits-ui";
let {
src,
alt,
fallback,
ref = $bindable(null),
imageRef = $bindable(null),
fallbackRef = $bindable(null),
...restProps
}: WithoutChildrenOrChild<Avatar.RootProps> & {
src: string;
alt: string;
fallback: string;
imageRef?: HTMLImageElement | null;
fallbackRef?: HTMLElement | null;
} = $props();
</script>
<Avatar.Root {...restProps} bind:ref>
<Avatar.Image {src} {alt} bind:ref={imageRef} />
<Avatar.Fallback bind:ref={fallbackRef}>
{fallback}
</Avatar.Fallback>
</Avatar.Root>
그런 다음 앱 곳곳에서 이렇게 사용하면 돼요.
+page.svelte
<script lang="ts">
import UserAvatar from "$lib/components/UserAvatar.svelte";
const users = [
{ handle: "huntabyte", initials: "HJ" },
{ handle: "pavelstianko", initials: "PS" },
{ handle: "adriangonz97", initials: "AG" },
];
</script>
{#each users as user}
<UserAvatar
src="https://github.com/{user.handle}.png"
alt="{user.name}'s avatar"
fallback={user.initials}
/>
{/each}
커스터마이징(Customization)
로딩 검사 건너뛰기(Skip Loading Check)
로컬 에셋처럼 이미지가 반드시 로드될 거라고 확신하는 경우에는 로딩 검사를 건너뛸 수 있어요.
<script lang="ts">
import { Avatar } from "bits-ui";
// local asset that's guaranteed to be available
import localAvatar from "/avatar.png";
</script>
<Avatar.Root loadingStatus="loaded">
<Avatar.Image src={localAvatar} alt="User avatar" />
<Avatar.Fallback>HB</Avatar.Fallback>
</Avatar.Root>
예제(Examples)
클릭 가능한 링크 미리보기 아바타(Clickable with Link Preview)
링크 미리보기(Link Preview)와 조합해 클릭 가능한 아바타를 만드는 방법을 보여주는 예시예요.
코드 펼치기(Expand Code)
<script lang="ts">
import { Avatar, LinkPreview } from "bits-ui";
import CalendarBlank from "phosphor-svelte/lib/CalendarBlank";
import MapPin from "phosphor-svelte/lib/MapPin";
</script>
<LinkPreview.Root>
<LinkPreview.Trigger
href="https://x.com/huntabyte"
target="_blank"
rel="noreferrer noopener"
class="rounded-xs underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-8 focus-visible:outline-black"
>
<Avatar.Root
class="data-[status=loaded]:border-foreground bg-muted text-muted-foreground h-12 w-12 rounded-full border border-transparent text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
</LinkPreview.Trigger>
<LinkPreview.Content
class="border-muted bg-background shadow-popover w-[331px] rounded-xl border p-[17px]"
sideOffset={8}
>
<div class="flex space-x-4">
<Avatar.Root
class="data-[status=loaded]:border-foreground bg-muted text-muted-foreground h-12 w-12 rounded-full border border-transparent text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
<div class="space-y-1 text-sm">
<h4 class="font-medium">@huntabyte</h4>
<p>I do things on the internet.</p>
<div
class="text-muted-foreground flex items-center gap-[21px] pt-2 text-xs"
>
<div class="flex items-center text-xs">
<MapPin class="mr-1 size-4" />
<span> FL, USA </span>
</div>
<div class="flex items-center text-xs">
<CalendarBlank class="mr-1 size-4" />
<span> Joined May 2020</span>
</div>
</div>
</div>
</div>
</LinkPreview.Content>
</LinkPreview.Root>
API 참조(API Reference)
Avatar.Root
아바타의 상태를 설정하고 관리하는 데 쓰는 루트 컴포넌트예요.
| Property | Type | Description | Details |
|---|---|---|---|
loadingStatus $bindable |
enum - 'loading' | 'loaded' | 'error' |
The loading status of the avatars source image. You can bind a variable to track the status outside of the component and use it to show a loading indicator or error message.Default: —— undefined |
|
onLoadingStatusChange |
function - (status: LoadingStatus) => void |
A callback function called when the loading status of the image changes.Default: —— undefined |
|
delayMs |
number |
How long to wait before showing the image after it has loaded. This can be useful to prevent a harsh flickering effect when the image loads quickly.Default: 0 |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-status |
enum - 'loading' | 'loaded' | 'error' |
The loading status of the image. | |
data-avatar-root |
'' |
Present on the root element. |
Avatar.Image
로딩이 끝난 뒤 표시되는 아바타 이미지예요.
| Property | Type | Description | Details |
|---|---|---|---|
ref $bindable |
HTMLImageElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-status |
enum - 'loading' | 'loaded' | 'error' |
The loading status of the image. | |
data-avatar-image |
'' |
Present on the root element. |
Avatar.Fallback
아바타 이미지가 로딩 중이거나 로드에 실패했을 때 보여주는 대체 요소예요.
| Property | Type | Description | Details |
|---|---|---|---|
ref $bindable |
HTMLSpanElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-status |
enum - 'loading' | 'loaded' | 'error' |
The loading status of the image. | |
data-avatar-fallback |
'' |
Present on the fallback element. |
더 알아보기 (Learn more)
이미지를 특정 비율로 잘라서 보여주고 싶다면 화면 비율(Aspect Ratio) 컴포넌트를 함께 보면 좋아요. 반응형 프로필 UI를 만들 때 아바타와 링크 미리보기(Link Preview)를 조합하는 패턴도 자주 쓰인답니다.