아바타
아바타 (Avatar)
쉽게 커스터마이즈할 수 있는 고품질 비스타일(unstyled) React avatar 컴포넌트예요. 프로필 사진, 이니셜, 폴백 아이콘을 표시할 때 사용해요.
출처: Base UI Avatar
본문
사용자의 프로필 사진을 표시하는 컴포넌트예요. 사진이 로드되기 전이나 실패했을 때 보여줄 폴백(fallback)을 제공하고, 이미지를 미리 로드(preload)하거나 그 자리에서(keepMounted) 로드할 수 있게 해줘요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import { Avatar } from '@base-ui/react/avatar';
export default function ExampleAvatar() {
return (
<div className="flex gap-4">
<Avatar.Root className="inline-flex size-8 items-center justify-center overflow-hidden rounded-full bg-neutral-200 align-middle text-sm leading-none font-normal text-neutral-950 select-none dark:bg-neutral-800 dark:text-white">
<Avatar.Image
src="https://images.unsplash.com/photo-1543610892-0b1f7e6d8ac1?w=128&h=128&dpr=2&q=80"
width="48"
height="48"
className="size-full object-cover"
/>
<Avatar.Fallback delay={600} className="flex size-full items-center justify-center text-sm">
LT
</Avatar.Fallback>
</Avatar.Root>
<Avatar.Root className="inline-flex size-8 items-center justify-center overflow-hidden rounded-full bg-neutral-200 align-middle text-sm leading-none font-normal text-neutral-950 select-none dark:bg-neutral-800 dark:text-white">
LT
</Avatar.Root>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Root {
display: inline-flex;
justify-content: center;
align-items: center;
vertical-align: middle;
border-radius: 100%;
-webkit-user-select: none;
user-select: none;
font-weight: 400;
color: oklch(14.5% 0 0deg);
background-color: oklch(92.2% 0 0deg);
font-size: 0.875rem;
line-height: 1;
overflow: hidden;
height: 2rem;
width: 2rem;
@media (prefers-color-scheme: dark) {
color: white;
background-color: oklch(26.9% 0 0deg);
}
}
.Image {
object-fit: cover;
height: 100%;
width: 100%;
}
.Fallback {
align-items: center;
display: flex;
justify-content: center;
height: 100%;
width: 100%;
font-size: 0.875rem;
}
/* index.tsx */
import { Avatar } from '@base-ui/react/avatar';
import styles from './index.module.css';
export default function ExampleAvatar() {
return (
<div style={{ display: 'flex', gap: '1rem' }}>
<Avatar.Root className={styles.Root}>
<Avatar.Image
src="https://images.unsplash.com/photo-1543610892-0b1f7e6d8ac1?w=128&h=128&dpr=2&q=80"
width="48"
height="48"
className={styles.Image}
/>
<Avatar.Fallback delay={600} className={styles.Fallback}>
LT
</Avatar.Fallback>
</Avatar.Root>
<Avatar.Root className={styles.Root}>LT</Avatar.Root>
</div>
);
}
구조 (Anatomy)
컴포넌트를 임포트하고 파트를 조립해요.
import { Avatar } from '@base-ui/react/avatar';
<Avatar.Root>
<Avatar.Image src="" />
<Avatar.Fallback>LT</Avatar.Fallback>
</Avatar.Root>;
최적화 및 지연 로드 이미지 (Optimized and lazy-loaded images)
기본적으로 <Avatar.Image>는 src를 미리 로드하고 이미지가 로드된 후에만 렌더링해요. 이 방식은 next/image처럼 원시 src와 다른 URL을 제공하는 이미지 최적화 도구나 loading="lazy"와는 잘 맞지 않아요.
keepMounted prop을 추가하면 이미지 요소를 즉시 렌더링하고 그 자리에서 로드하게 해요. 실제로 표시되는 이미지만 요청돼요:
import Image from 'next/image';
<Avatar.Root>
<Avatar.Fallback>LT</Avatar.Fallback>
<Avatar.Image keepMounted render={<Image src="/avatar.png" width={32} height={32} alt="" />} />
</Avatar.Root>;
스태킹 (Stacking)
keepMounted를 쓰면 이미지가 로드될 때까지 이미지와 폴백이 모두 존재해요. 그때까지 이미지는 보조 기술(assistive technology)에 숨겨지므로, 폴백이 접근 가능한 이름을 스스로 제공해요.
둘을 같은 상자에 쌓고, <Avatar.Image>를 <Avatar.Fallback> 뒤에 배치하세요. 둘 다 위치가 지정되므로 DOM에서 나중에 오는 쪽이 위에 그려져요. 그러면 폴백이 이미지로 덮일 때까지 아래로 보여요.
로딩 중인 이미지는 아무것도 그리지 않으므로 폴백이 스스로 드러나요. 로드에 실패한 이미지는 그 위에 깨진 이미지 아이콘을 그려요. 두 상태 모두 data-loading과 data-error 속성으로 이미지를 숨길 수 있어요:
.Root {
position: relative;
}
.Image,
.Fallback {
position: absolute;
inset: 0;
}
.Image[data-loading],
.Image[data-error] {
visibility: hidden;
}
여기서 display: none은 피하세요. 박스가 없는 요소는 뷰포트와 교차하지 않으므로 loading="lazy"가 이미지를 가져오지 않게 돼요. visibility와 opacity는 둘 다 지연 로딩을 계속 동작하게 해요.
서버 렌더링 (Server rendering)
keepMounted를 쓰면 이미지가 서버 렌더링된 HTML의 일부가 되어 하이드레이션 전에 로드를 시작해요. 폴백도 마찬가지로, 하이드레이션이 로딩 상태를 해결할 때까지 표시돼요. 캐시된 이미지는 진입 애니메이션 없이 즉시 표시돼요.
API 레퍼런스
Root
사용자의 프로필 사진, 이니셜, 또는 폴백 아이콘을 표시해요.
<span> 요소를 렌더링해요.
Root Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| className | string \| ((state: Avatar.Root.State) => string \| undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태에 따라 클래스를 반환하는 함수. |
| style | React.CSSProperties \| ((state: Avatar.Root.State) => React.CSSProperties \| undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수. |
| render | ReactElement \| ((props: HTMLProps, state: Avatar.Root.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Root.Props
Root props의 재내보내기예요.
Root.State
type AvatarRootState = {
/** The image loading status. */
imageLoadingStatus: ImageLoadingStatus;
};
Image
아바타에 표시할 이미지예요.
<img> 요소를 렌더링해요.
Image Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| onLoadingStatusChange | ((status: ImageLoadingStatus) => void) |
- | 로딩 상태가 변경될 때 호출되는 콜백. |
| className | string \| ((state: Avatar.Image.State) => string \| undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태에 따라 클래스를 반환하는 함수. |
| style | React.CSSProperties \| ((state: Avatar.Image.State) => React.CSSProperties \| undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수. |
| keepMounted | boolean |
false |
이미지 요소를 마운트된 상태로 유지하고 미리 로드하는 대신 그 자리에서 로드할지 여부.
loading="lazy"와 next/image 같은 최적화된 이미지 컴포넌트를 지원해요. |
| render | ReactElement \| ((props: React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, state: Avatar.Image.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Image Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-error | - | 이미지 로드에 실패했을 때 존재해요. |
| data-loading | - | 이미지가 로딩 중일 때 존재해요. |
| data-starting-style | - | 이미지가 들어오는 애니메이션을 시작할 때 존재해요. |
| data-ending-style | - | 이미지가 나가는 애니메이션을 할 때 존재해요. |
Image.Props
Image props의 재내보내기예요.
Image.State
type AvatarImageState = {
/** The transition status of the component. */
transitionStatus: TransitionStatus;
/** The image loading status. */
imageLoadingStatus: ImageLoadingStatus;
};
Fallback
이미지 로드에 실패했거나 이미지가 제공되지 않았을 때 렌더링돼요.
<span> 요소를 렌더링해요.
Fallback Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| delay | number |
0 |
폴백을 표시하기 전에 기다리는 시간(밀리초). |
| className | string \| ((state: Avatar.Fallback.State) => string \| undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태에 따라 클래스를 반환하는 함수. |
| style | React.CSSProperties \| ((state: Avatar.Fallback.State) => React.CSSProperties \| undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수. |
| render | ReactElement \| ((props: HTMLProps, state: Avatar.Fallback.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Fallback.Props
Fallback props의 재내보내기예요.
Fallback.State
type AvatarFallbackState = {
/** The image loading status. */
imageLoadingStatus: ImageLoadingStatus;
};
Additional Types
ImageLoadingStatus
type ImageLoadingStatus = 'idle' | 'loading' | 'loaded' | 'error';
Export Groups
Avatar.Root:Avatar.Root,Avatar.Root.State,Avatar.Root.PropsAvatar.Image:Avatar.Image,Avatar.Image.State,Avatar.Image.PropsAvatar.Fallback:Avatar.Fallback,Avatar.Fallback.State,Avatar.Fallback.PropsDefault:ImageLoadingStatus,AvatarRootState,AvatarRootProps,AvatarImageState,AvatarImageProps,AvatarFallbackState,AvatarFallbackProps
Canonical Types
Canonical: Alias 매핑 — Canonical의 네임스페이스가 이미 임포트되어 있으면 Canonical을, 아니면 Alias를 사용하세요.
Avatar.Root.State:AvatarRootStateAvatar.Root.Props:AvatarRootPropsAvatar.Image.State:AvatarImageStateAvatar.Image.Props:AvatarImagePropsAvatar.Fallback.State:AvatarFallbackStateAvatar.Fallback.Props:AvatarFallbackProps