ScaleRocket/Mobile

Avatar

Composant Avatar avec fallback d'initiales, support d'image et tailles multiples.

Avatar

Le composant Avatar affiche la photo de profil d'un utilisateur avec un fallback automatique d'initiales quand aucune image n'est disponible.

Utilisation de base

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

// Avec image
<Avatar source={{ uri: user.avatarUrl }} name={user.name} />

// Sans image (affiche les initiales)
<Avatar name="John Doe" />

Tailles

Quatre tailles intégrées :

<Avatar name="John Doe" size="xs" />  {/* 24x24 */}
<Avatar name="John Doe" size="sm" />  {/* 32x32 */}
<Avatar name="John Doe" size="md" />  {/* 48x48 */}
<Avatar name="John Doe" size="lg" />  {/* 64x64 */}
TailleDimensionsTaille policeCas d'usage
xs24x2410Mentions en ligne
sm32x3212Éléments de liste
md48x4818Cartes, en-têtes
lg64x6424Écrans de profil

Fallback d'initiales

Quand aucune source n'est fournie, le composant extrait les initiales du name :

function getInitials(name: string): string {
  const parts = name.trim().split(" ");
  if (parts.length === 1) return parts[0][0].toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

Exemples :

  • "John Doe" affiche JD
  • "Alice" affiche A
  • "John Michael Smith" affiche JS

Couleurs de fond

Les avatars à initiales reçoivent une couleur de fond déterministe basée sur le nom :

const COLORS = [
  "#3B82F6", "#EF4444", "#10B981", "#F59E0B",
  "#8B5CF6", "#EC4899", "#14B8A6", "#F97316",
];

function getColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return COLORS[Math.abs(hash) % COLORS.length];
}

Cela garantit que le même utilisateur obtient toujours la même couleur.

Chargement d'image

Le composant gère les états de chargement d'image :

import { useState } from "react";
import { Image, View, Text } from "react-native";

function Avatar({ source, name, size = "md" }: AvatarProps) {
  const [imageError, setImageError] = useState(false);
  const dimensions = SIZES[size];

  if (source && !imageError) {
    return (
      <Image
        source={source}
        style={{
          width: dimensions,
          height: dimensions,
          borderRadius: dimensions / 2,
        }}
        onError={() => setImageError(true)}
      />
    );
  }

  return (
    <View
      style={{
        width: dimensions,
        height: dimensions,
        borderRadius: dimensions / 2,
        backgroundColor: getColor(name),
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Text style={{ color: "white", fontSize: FONT_SIZES[size] }}>
        {getInitials(name)}
      </Text>
    </View>
  );
}

Groupe d'avatars

Affichez plusieurs avatars empilés :

function AvatarGroup({ users, max = 3 }: { users: User[]; max?: number }) {
  const visible = users.slice(0, max);
  const remaining = users.length - max;

  return (
    <View style={{ flexDirection: "row" }}>
      {visible.map((user, i) => (
        <View key={user.id} style={{ marginLeft: i > 0 ? -8 : 0, zIndex: max - i }}>
          <Avatar source={{ uri: user.avatarUrl }} name={user.name} size="sm" />
        </View>
      ))}
      {remaining > 0 && (
        <View style={styles.overflow}>
          <Text style={styles.overflowText}>+{remaining}</Text>
        </View>
      )}
    </View>
  );
}

Avec badge

Ajoutez un indicateur en ligne ou un badge de notification :

function AvatarWithBadge({ user, isOnline }: Props) {
  return (
    <View>
      <Avatar source={{ uri: user.avatarUrl }} name={user.name} size="md" />
      {isOnline && (
        <View
          style={{
            position: "absolute",
            bottom: 0,
            right: 0,
            width: 14,
            height: 14,
            borderRadius: 7,
            backgroundColor: "#10B981",
            borderWidth: 2,
            borderColor: "white",
          }}
        />
      )}
    </View>
  );
}

Props du composant

PropTypeDéfautDescription
namestringrequisNom d'affichage de l'utilisateur
sourceImageSourceSource de l'image (uri)
size"xs" | "sm" | "md" | "lg""md"Taille de l'avatar
styleViewStyleStyle du conteneur

On this page