useAvatar
Hooks that manage avatar image loading state and group layout.
Usage#
import { useAvatar } from '@primereact/headless/avatar';
import { useAvatarGroup } from '@primereact/headless/avatargroup';
const { rootProps, state, handleImageLoad, handleImageUnload } = useAvatar();
return <div {...rootProps}></div>;useAvatar manages the image loading lifecycle while useAvatarGroup provides root props for grouping — see Primitive for a component-based API.
Features#
- Image loading lifecycle management with
handleImageLoadandhandleImageUnload state.loadfor conditional rendering between image and fallback content- Configurable
delayDurationfor delayed image reveal useAvatarGroupfor grouping multiple avatars with shared data attributes
Behavior#
Image Loading#
Call handleImageLoad(src) to begin loading an image. The hook creates a hidden Image object, listens for load and error events, and sets state.load to true on success or false on failure.
const { state, handleImageLoad, handleImageUnload } = useAvatar();
React.useEffect(() => {
handleImageLoad('https://example.com/photo.png');
return () => handleImageUnload();
}, []);Always call handleImageUnload on cleanup to remove event listeners and reset state.
Fallback Content#
Use state.load to conditionally render either the image or fallback content. Fallback can be text initials, an icon, or any custom element.
<div {...rootProps}>{state.load ? <img src="https://example.com/photo.png" alt="User" /> : <span>AB</span>}</div>Delay Duration#
Use delayDuration to introduce a delay before revealing the loaded image. This prevents layout flash when images load near-instantly.
const avatar = useAvatar({ delayDuration: 300 });The default value is 0 (no delay).
Avatar Group#
Use useAvatarGroup to wrap multiple avatars. The hook returns rootProps with data attributes for styling the group container.
const { rootProps: groupRootProps } = useAvatarGroup();
<div {...groupRootProps}>{/* multiple avatar elements */}</div>;Custom Styling with Data Attributes#
Every prop object includes data-scope and data-part attributes for CSS targeting.
[data-scope='avatar'][data-part='root'] {
width: 3rem;
height: 3rem;
border-radius: 50%;
overflow: hidden;
}
[data-scope='avatargroup'][data-part='root'] {
display: flex;
align-items: center;
}
[data-scope='avatargroup'][data-part='root'] > [data-scope='avatar'] {
margin-left: -0.75rem;
}API#
useAvatar#
| Name | Type | Default |
|---|---|---|
delayDuration | number | — |
| The delay duration of the avatar. | ||
useAvatarGroup#
| Name | Type | Default |
|---|---|---|
Accessibility#
See Avatar Primitive for WAI-ARIA compliance details and keyboard support.