Avatar

Rust/UI component that displays an avatar with image and fallback support.

  • Rust/UI Icons - CopyCopy Demo
@rustify.rs
RS
use leptos::prelude::*;

use crate::components::ui::avatar::{Avatar, AvatarFallback, AvatarImage};

#[component]
pub fn DemoAvatar() -> impl IntoView {
    view! {
        <Avatar>
            <AvatarImage attr:src="/broken-image.png" attr:alt="@rustify.rs" />
            <AvatarFallback>RS</AvatarFallback>
        </Avatar>
    }
}

Installation

You can run either of the following commands:

# cargo install ui-cli --force
ui add demo_avatar
ui add avatar

Update the imports to match your project setup.

Copy and paste the following code into your project:

components/ui/avatar.rs

use leptos::prelude::*;
use leptos_ui::clx;
use tw_merge::tw_merge;

mod components {
    use super::*;
    clx! {Avatar, div, "relative flex size-8 shrink-0 overflow-hidden rounded-full"}
    clx! {AvatarFallback, div, "bg-muted absolute inset-0 flex size-full items-center justify-center rounded-full"}
}

pub use components::*;

#[component]
pub fn AvatarImage(#[prop(into, optional)] class: String) -> impl IntoView {
    let merged_class = tw_merge!("absolute inset-0 aspect-square size-full", class);
    let node_ref = NodeRef::<leptos::html::Img>::new();

    view! {
        <img
            node_ref=node_ref
            class=merged_class
            on:error=move |_| {
                if let Some(img) = node_ref.get() {
                    let _ = img.set_attribute("style", "display: none;");
                }
            }
        />
    }
}

Update the imports to match your project setup.

Usage

use crate::components::ui::avatar::{
    Avatar,
    AvatarImage,
    AvatarFallback,
};
<Avatar>
    <AvatarImage attr:src="/path/to/image.png" attr:alt="@username" />
    <AvatarFallback>UN</AvatarFallback>
</Avatar>