Avatar

An image element with a fallback for representing the user.

Stimulus: shadcn--avatar
Shadcn

Installation

Add the component to your project:

rails generate shadcn:component avatar

Usage

<%= render Shadcn::AvatarComponent.new(
  src: "https://github.com/shadcn.png",
  alt: "Shadcn",
  fallback: "CN"
) %>

Examples

With Image

Shadcn

Fallback

When no image is provided or the image fails to load, a fallback is shown.

JD JS AB

Sizes

Small Default Large Extra Large

Fallback Sizes

SM DF LG XL

User List

Shadcn

Shadcn

shadcn@example.com

JD

John Doe

john@example.com

JS

Jane Smith

jane@example.com

Avatar Group

User 1 JD AB +3

API Reference

API Reference

Prop Type Default Description
src String nil Image URL for the avatar
alt String "" Alt text for the image
fallback String nil Fallback text when image is unavailable (auto-generated from alt if not provided)
size Symbol :default Avatar size (:sm, :default, :lg, :xl)
class_name String nil Additional CSS classes to apply

Size Reference

Size Dimensions Font Size
:sm 32x32px (h-8 w-8) text-xs
:default 40x40px (h-10 w-10) text-sm
:lg 48x48px (h-12 w-12) text-base
:xl 64x64px (h-16 w-16) text-lg

Stimulus Controller

This component requires JavaScript. The Stimulus controller docs provides interactivity.

Handles image loading errors and shows fallback when image fails to load.

Installation

Add to your config/importmap.rb:

pin "shadcn-rails", to: "shadcn/index.js"

Then in your app/javascript/controllers/index.js:

import { Application } from "@hotwired/stimulus"
import { registerShadcnControllers } from "shadcn-rails"

const application = Application.start()
registerShadcnControllers(application)

Or import just this controller:

import DocsController from "shadcn-rails/controllers/docs_controller"

application.register("docs", DocsController)

Targets

Name Description
image The avatar image element
fallback The fallback element shown when image fails

Actions

Action Description
handleError Called when image fails to load, shows fallback

TypeScript

Type definitions are included. Import types as needed:

import type { DocsController } from "shadcn-rails"

Accessibility

  • Always provide meaningful alt text for the avatar
  • The fallback text is visible to screen readers when shown
  • If the avatar is decorative (e.g., displayed alongside a name), you can use an empty alt: alt: ""