84 lines
1.8 KiB
TypeScript
Executable File
84 lines
1.8 KiB
TypeScript
Executable File
import classNames from "classnames";
|
|
import React from "react";
|
|
|
|
export type Props = {
|
|
/**
|
|
* The style avatar
|
|
*/
|
|
className?: string;
|
|
/**
|
|
* The path of image
|
|
*/
|
|
src?: string;
|
|
/**
|
|
* The alternative text in case the image is not valid
|
|
*/
|
|
alt?: string;
|
|
/**
|
|
* The text inside avatar as a child
|
|
*/
|
|
children?: React.ReactNode;
|
|
};
|
|
|
|
// Choosing random color for the avatar background
|
|
function getRandomInt(max: number) {
|
|
return Math.floor(Math.random() * max);
|
|
}
|
|
let colors: string[] = [
|
|
"bg-red-400",
|
|
"bg-orange-400",
|
|
"bg-green-400",
|
|
"bg-amber-400",
|
|
"bg-yellow-400",
|
|
"bg-lime-400",
|
|
"bg-emerald-400",
|
|
"bg-teal-400",
|
|
"bg-cyan-400",
|
|
"bg-sky-400",
|
|
"bg-blue-400",
|
|
"bg-indigo-400",
|
|
"bg-violet-400",
|
|
"bg-purple-400",
|
|
"bg-fuchsia-400",
|
|
];
|
|
|
|
const Avatar = ({ className, src, alt, children }: Props) => {
|
|
const wrapperClasses = src ? "" : colors[getRandomInt(colors.length)];
|
|
const position = src ? "relative pt-[100%]" : "";
|
|
return (
|
|
<div
|
|
className={classNames(
|
|
wrapperClasses,
|
|
position,
|
|
"rounded-full ",
|
|
className
|
|
)}
|
|
>
|
|
{/* In case the src is valid, it will show the image */}
|
|
{src && (
|
|
<img
|
|
className={classNames(
|
|
"h-9 w-9 rounded-full absolute top-1/2 left-1/2 object-cover -translate-x-1/2 -translate-y-1/2",
|
|
className
|
|
)}
|
|
src={src}
|
|
alt={alt}
|
|
/>
|
|
)}
|
|
{/* The text will be shown in case it is valid */}
|
|
{children && (
|
|
<div
|
|
className={classNames(
|
|
"h-9 w-9 flex justify-center items-center text-base text-white",
|
|
className
|
|
)}
|
|
>
|
|
{children}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default Avatar;
|