AniUI

Avatar

User avatar with image and fallback initials.

import { Avatar } from "@/components/ui/avatar";

export function MyScreen() {
  return (
    <Avatar
      src="https://github.com/anishlp7.png"
      fallback="AN"
    />
  );
}

Installation

npx @aniui/cli add avatar

Usage

app/index.tsx
import { Avatar } from "@/components/ui/avatar";

export function MyScreen() {
  return (
    <Avatar
      src="https://github.com/anishlp7.png"
      fallback="AN"
    />
  );
}

Sizes

SM
MD
LG
<Avatar size="sm" fallback="SM" />
<Avatar size="md" fallback="MD" />
<Avatar size="lg" fallback="LG" />

Fallback

When no image source is provided or the image fails to load, the fallback initials are displayed.

AB
?
<Avatar fallback="AB" />
<Avatar fallback="?" />

Props

PropTypeDefault
size
"sm" | "md" | "lg"
"md"
src
string
fallback
string
"?"
className
string

Also accepts all View props from React Native.

Source

components/ui/avatar.tsx
import React, { useState } from "react";
import { View, Image, Text } from "react-native";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";

const avatarVariants = cva("items-center justify-center rounded-full bg-muted overflow-hidden", {
  variants: {
    size: {
      sm: "h-8 w-8",
      md: "h-10 w-10",
      lg: "h-14 w-14",
    },
  },
  defaultVariants: {
    size: "md",
  },
});
const avatarTextVariants = cva("font-medium text-muted-foreground", {
  variants: {
    size: {
      sm: "text-xs",
      md: "text-sm",
      lg: "text-lg",
    },
  },
  defaultVariants: {
    size: "md",
  },
});
export interface AvatarProps
  extends React.ComponentPropsWithoutRef<typeof View>,
    VariantProps<typeof avatarVariants> {
  className?: string;
  src?: string;
  fallback?: string;
}
export function Avatar({ size, className, src, fallback, ...props }: AvatarProps) {
  const [hasError, setHasError] = useState(false);
  return (
    <View className={cn(avatarVariants({ size }), className)} {...props}>
      {src && !hasError ? (
        <Image
          source={{ uri: src }}
          className="h-full w-full"
          resizeMode="cover"
          onError={() => setHasError(true)}
        />
      ) : (
        <Text className={cn(avatarTextVariants({ size }))}>{fallback ?? "?"}</Text>
      )}
    </View>
  );
}