import React, { useState, useEffect } from "react"; // A simple hash function to generate a deterministic value from the name function hashString(str) { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; } return hash; } const Avatar = ({ firstName, lastName, size = "sm", classAvatar }) => { // Combine firstName and lastName to create a unique string for hashing const fullName = `${firstName} ${lastName}`; const [bgClass, setBgClass] = useState(""); // Function to generate the avatar text function generateAvatarText(firstName, lastName) { if (!firstName) return ""; if (!lastName || lastName.trim() === "") { return firstName.slice(0, 2).toUpperCase(); } return `${firstName[0]}${lastName[0]}`.toUpperCase(); } // Function to map the hash value to a Bootstrap background class function getBgClassFromHash(hash) { const bgClasses = [ "bg-primary", "bg-secondary", "bg-success", "bg-danger", "bg-warning", "bg-info", "bg-dark", "text-light", ]; // Use the hash value to pick a background color from the array const index = Math.abs(hash % bgClasses.length); return bgClasses[index]; } useEffect(() => { // Generate the hash from the full name and map it to a background class const hash = hashString(fullName); setBgClass(getBgClassFromHash(hash)); }, [fullName]); // Re-run if the fullName changes return (
{generateAvatarText(firstName, lastName)}
); }; export default Avatar;