|
| 1 | +import React from "react"; |
| 2 | +import { Image, View, Text, ImageSourcePropType, StyleProp, ImageStyle, ViewStyle, TextStyle } from "react-native"; |
| 3 | + |
| 4 | +export interface AvatarProps { |
| 5 | + imageSource?: ImageSourcePropType; |
| 6 | + size?: number; // in dp |
| 7 | + containerStyle?: StyleProp<ViewStyle>; |
| 8 | + fallbackText?: string; |
| 9 | + textStyle?: StyleProp<TextStyle>; |
| 10 | + imageStyle?: StyleProp<ImageStyle>; |
| 11 | +} |
| 12 | + |
| 13 | +// Note: By default, the container uses overflow: "hidden" and a borderRadius |
| 14 | +// of size/2 for a circular shape. If you pass any additional containerStyle, |
| 15 | +// it will merge with these defaults. |
| 16 | + |
| 17 | +export function Avatar({ imageSource, size = 40, containerStyle, fallbackText, textStyle, imageStyle }: AvatarProps) { |
| 18 | + return ( |
| 19 | + <View |
| 20 | + style={[ |
| 21 | + { |
| 22 | + width: size, |
| 23 | + height: size, |
| 24 | + borderRadius: size / 2, // Circular! |
| 25 | + overflow: "hidden", |
| 26 | + alignItems: "center", |
| 27 | + justifyContent: "center", |
| 28 | + }, |
| 29 | + containerStyle, |
| 30 | + ]}> |
| 31 | + {imageSource ? ( |
| 32 | + // Fill the container if theres an image |
| 33 | + <Image |
| 34 | + source={imageSource} |
| 35 | + style={[ |
| 36 | + { |
| 37 | + width: "100%", |
| 38 | + height: "100%", |
| 39 | + borderRadius: size / 2, // Circular! |
| 40 | + resizeMode: "cover", |
| 41 | + }, |
| 42 | + imageStyle, |
| 43 | + ]} |
| 44 | + /> |
| 45 | + ) : fallbackText ? ( |
| 46 | + // Display fallback text if no image |
| 47 | + <Text style={textStyle}>{fallbackText}</Text> |
| 48 | + ) : null} |
| 49 | + </View> |
| 50 | + ); |
| 51 | +} |
| 52 | + |
| 53 | +// Example usage: |
| 54 | + |
| 55 | +// <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> |
| 56 | +// {/* with image source */} |
| 57 | +// <Avatar |
| 58 | +// imageSource={{ uri: "https://course.khoury.northeastern.edu/cs2510a/ben_lerner.jpg" }} |
| 59 | +// size={50} |
| 60 | +// imageStyle={{ resizeMode: "cover" }} |
| 61 | +// /> |
| 62 | + |
| 63 | +// {/* with fallback text */} |
| 64 | +// <Avatar |
| 65 | +// fallbackText="AB" |
| 66 | +// size={40} |
| 67 | +// containerStyle={{ |
| 68 | +// backgroundColor: "#007AFF", |
| 69 | +// }} |
| 70 | +// textStyle={{ |
| 71 | +// fontWeight: "bold", |
| 72 | +// }} |
| 73 | +// /> |
| 74 | +// </View> |
0 commit comments