Skip to content

Instantly share code, notes, and snippets.

@usmansbk
Created May 1, 2020 15:41
Show Gist options
  • Save usmansbk/7c08f7613b495e405ce99dda0fe545d3 to your computer and use it in GitHub Desktop.
Save usmansbk/7c08f7613b495e405ce99dda0fe545d3 to your computer and use it in GitHub Desktop.
import React from 'react';
import { View, Text, Image } from 'react-native';
import emojiRegex from 'emoji-regex';
const avatarColors = [
'red',
'blue',
'green'
];
function getAvatarBackgroundColor(name) {
const colorIndex = name.length % avatarColors.length;
return avatarColors[colorIndex];
}
function getInitials(name) {
if (!name) return 'John Doe';
const emojiMatch = emojiRegex().exec(name);
let avatarName;
if (emojiMatch) {
avatarName = emojiMatch[0];
} else {
const [ first, second ] = name.split(' ');
avatarName = `${first[0]} ${second ? second[0] : ''}`.toUpperCase();
}
return avatarName;
}
export default ({
src, // url to image
size=64,
name
}) => {
const initials = getInitials(name);
const bgColor = getAvatarBackgroundColor(name);
const style = {
width: size,
height: size,
borderRadius: size / 2,
backgroundColor: src ? 'transparent' : bgColor,
justifyContent: 'center',
alignItems: 'center'
};
const textStyle = {
fontSize: 24,
color: 'white'
};
return (
<View style={style}>
{
src ? (
<Image
style={style}
source={{uri: src}}
/>
) : (
<Title
style={textStyle}
adjustsFontSizeToFit>{initials}</Title>
)
}
</View>
)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment