Skip to content

Instantly share code, notes, and snippets.

@jordiup
Created May 27, 2023 02:49
Show Gist options
  • Save jordiup/a07b3c5a6933d74ffb5924e0eee8d471 to your computer and use it in GitHub Desktop.
Save jordiup/a07b3c5a6933d74ffb5924e0eee8d471 to your computer and use it in GitHub Desktop.
# Nativebase Avatar with Coloured Text (Chakra UI Equivalent)
import React from 'react';
import ColorHash from 'color-hash';
import { Circle, ICircleProps, Image, Text } from 'native-base';
type Props = {
firstName: string;
lastName?: string;
name?: string;
size?: string;
src?: string;
} & ICircleProps;
const CustomAvatar = ({
firstName,
lastName,
name,
size,
src,
...boxProps
}: Props) => {
let _name = name ?? `${firstName} ${lastName}`;
let _size: string | number;
switch (size) {
case '2xs':
_size = 4;
break;
case 'xs':
_size = 6;
break;
case 'sm':
_size = 8;
break;
case 'md':
_size = 12;
break;
case 'lg':
_size = 16;
break;
case 'xl':
_size = 24;
break;
case '2xl':
_size = 32;
break;
default:
_size = 12;
break;
}
const colorHashLight = new ColorHash({ saturation: 1.0, lightness: 0.6 });
const colorHashDark = new ColorHash({ saturation: 1.0, lightness: 0.1 });
const cLight = colorHashLight.hex(_name);
const cDark = colorHashDark.hex(_name);
const initials = _name
.split(' ')
.map((n) => n[0])
.join('');
return src ? (
<Circle
bg={cLight}
position="relative"
height={_size}
width={_size}
{...boxProps}
>
<Image
source={{ uri: src }}
alt={_name}
height={_size}
width={_size}
borderRadius={_size}
/>
</Circle>
) : (
<Circle
bg={cLight}
position="relative"
height={_size}
width={_size}
{...boxProps}
>
<Text color={cDark} fontSize={_size}>
{initials}
</Text>
</Circle>
);
};
export default CustomAvatar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment