Avatar
Fallback On Error
An avatar that falls back to initials on a real load error: the photo keeps an honest alt, and no broken-image icon takes its place.
- avatar
- fallback
- image
- error
Preview
Use it with AI
- 1. Copy the link.
- 2. Write to your agent in your own words and drop the link into the sentence.
- 3. The agent opens the link and installs the component from the registry.
put this in the header: https://vibeui.ru/c/avatar-029?lang=en
Show the full instructions
What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.
# Install and place "avatar-029" (Fallback On Error) from VibeUI
## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/avatar-029.json
Registry item: https://vibeui.ru/r/avatar-029.json
Installs to: components/vibeui/avatar-029.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.
Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.
## 2. What it is
An avatar that falls back to initials on a real load error: the photo keeps an honest alt, and no broken-image icon takes its place.
An avatar swapping the photo for initials on a load error: a real alt on the image and role="img" with the name after the failure. Zero dependencies, one file.
## 3. How to use it
import { Avatar029 } from "@/components/vibeui/avatar-029"
<Avatar029 name="Ilya Mokhov" src="/people/ilya.jpg" size="md" />
Read the installed file for the full prop list.
## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.
Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)
## 5. Keep exactly as installed
- the local --vibeui-avatar-029-* palette — do not swap it for your theme tokens
- the onError handler instead of a backdrop of initials: only it lets the photo keep an honest alt
- role="img" with aria-label after the failure — otherwise two letters read as loose characters
- treating an empty src as the same case: two paths to one result are not needed
- object-fit: cover — a portrait would otherwise stretch inside the circle
- the plain <img> instead of next/image: the component has to work in any React project
## 6. You may change
- name — the person's name; the initials and the colour come from it
- the photo URL through src
- the size through size — sm, md or lg
- the backdrop hue if you have your own palette
## 7. Rules
- The component is client-side precisely because of onError: if client code is unacceptable here, use the backdrop-initials variant.
- It never retries: when src changes, reset the state with a key on the component.
- Initials come from the first two words: a single-word name yields one letter, which is fine.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.
## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.For developers
npx shadcn@latest add https://vibeui.ru/r/avatar-029.jsonhttps://vibeui.ru/r/avatar-029.jsonКомпонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-avatar-029-*. Клиентский: "use client" и useState держат факт сбоя. Соседний вариант кладёт инициалы подложкой и обходится без JS, но платит за это пустым alt — фотография там обязана молчать. Здесь ошибка ловится onError, поэтому у картинки остаётся alt с именем, а после сбоя корень сам получает role="img" с aria-label. Пустой src считается тем же случаем: проверять «есть ли фото» дважды незачем.
Component source
The same file your agent installs. Here in case you would rather copy it by hand.
"use client"
import { useState } from "react"
import type { ComponentPropsWithoutRef, CSSProperties } from "react"
export type Avatar029Props = Omit<
ComponentPropsWithoutRef<"span">,
"children"
> & {
name?: string
src?: string
size?: "sm" | "md" | "lg"
}
// Идея компонента: подмена фотографии инициалами по настоящей ошибке загрузки.
// Соседний вариант кладёт инициалы подложкой и обходится без JS, но платит за
// это пустым alt: фотография там обязана молчать. Здесь ошибка ловится onError,
// поэтому у картинки остаётся честный alt с именем, а после сбоя вместо неё
// появляются инициалы — не значок сломанного изображения и не дырка в строке.
// Пустой src считается тем же случаем: проверять «есть ли фото» дважды незачем.
const STYLES = `
:where([data-vibeui-block="avatar-029"]){
--vibeui-avatar-029-size:2.75rem;
--vibeui-avatar-029-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="avatar-029"]{
display:inline-flex;align-items:center;justify-content:center;flex:none;
overflow:hidden;
width:var(--vibeui-avatar-029-size);height:var(--vibeui-avatar-029-size);
border-radius:9999px;
background:oklch(0.9 0.06 var(--vibeui-avatar-029-hue,265));
color:oklch(0.36 0.12 var(--vibeui-avatar-029-hue,265));
font-family:var(--vibeui-avatar-029-font);
font-size:calc(var(--vibeui-avatar-029-size) * 0.34);font-weight:700;line-height:1;
}
[data-vibeui-block="avatar-029"] [data-part="photo"]{
width:100%;height:100%;object-fit:cover;display:block;
}
[data-vibeui-block="avatar-029"][data-size="sm"]{--vibeui-avatar-029-size:2rem}
[data-vibeui-block="avatar-029"][data-size="lg"]{--vibeui-avatar-029-size:4rem}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="avatar-029"] *{animation:none!important;transition:none!important}}
`
function hue(name: string) {
let hash = 2166136261
for (const symbol of name) {
hash ^= symbol.codePointAt(0)!
hash = Math.imul(hash, 16777619)
}
return ((hash >>> 0) % 12) * 30
}
function initials(name: string) {
return name
.split(" ")
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join("")
}
/**
* Аватар, который сам переходит на инициалы по ошибке загрузки фотографии.
* Один файл, ноль зависимостей, собственная палитра.
*/
export function Avatar029({
name = "Илья Мохов",
src = "",
size = "md",
className,
style,
...props
}: Avatar029Props) {
const [failed, setFailed] = useState(false)
const showPhoto = src !== "" && !failed
const palette = {
"--vibeui-avatar-029-hue": hue(name),
...style,
} as CSSProperties
return (
<>
<style href="vibeui-avatar-029" precedence="medium">
{STYLES}
</style>
<span
{...props}
data-vibeui-block="avatar-029"
data-size={size}
data-fallback={!showPhoto}
className={className}
style={palette}
role={showPhoto ? undefined : "img"}
aria-label={showPhoto ? undefined : name}
>
{showPhoto ? (
// Настоящий alt: фотография не обязана молчать, как в вариантах без JS.
<img
data-part="photo"
src={src}
alt={name}
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
/>
) : (
<span aria-hidden="true">{initials(name)}</span>
)}
</span>
</>
)
}