UNPKG

2.36 kBTypeScriptView Raw
1import * as React from 'react';
2import {
3 View,
4 ViewStyle,
5 StyleSheet,
6 StyleProp,
7 TextStyle,
8} from 'react-native';
9import Text from '../Typography/Text';
10import { withTheme } from '../../core/theming';
11import { white } from '../../styles/colors';
12import getContrastingColor from '../../utils/getContrastingColor';
13
14const defaultSize = 64;
15
16type Props = React.ComponentPropsWithRef<typeof View> & {
17 /**
18 * Initials to show as the text in the `Avatar`.
19 */
20 label: string;
21 /**
22 * Size of the avatar.
23 */
24 size?: number;
25 /**
26 * Custom color for the text.
27 */
28 color?: string;
29 /**
30 * Style for text container
31 */
32 style?: StyleProp<ViewStyle>;
33 /**
34 * Style for the title.
35 */
36 labelStyle?: StyleProp<TextStyle>;
37 /**
38 * @optional
39 */
40 theme: ReactNativePaper.Theme;
41};
42
43/**
44 * Avatars can be used to represent people in a graphical way.
45 *
46 * <div class="screenshots">
47 * <figure>
48 * <img class="medium" src="screenshots/avatar-text.png" />
49 * </figure>
50 * </div>
51 *
52 * ## Usage
53 * ```js
54 * import * as React from 'react';
55 * import { Avatar } from 'react-native-paper';
56 *
57 * const MyComponent = () => (
58 * <Avatar.Text size={24} label="XD" />
59 * );
60 * ```
61 */
62const AvatarText = ({
63 label,
64 size = defaultSize,
65 style,
66 theme,
67 labelStyle,
68 color: customColor,
69 ...rest
70}: Props) => {
71 const { backgroundColor = theme.colors.primary, ...restStyle } =
72 StyleSheet.flatten(style) || {};
73 const textColor =
74 customColor ??
75 getContrastingColor(backgroundColor, white, 'rgba(0, 0, 0, .54)');
76
77 return (
78 <View
79 style={[
80 {
81 width: size,
82 height: size,
83 borderRadius: size / 2,
84 backgroundColor,
85 },
86 styles.container,
87 restStyle,
88 ]}
89 {...rest}
90 >
91 <Text
92 style={[
93 styles.text,
94 {
95 color: textColor,
96 fontSize: size / 2,
97 lineHeight: size,
98 },
99 labelStyle,
100 ]}
101 numberOfLines={1}
102 >
103 {label}
104 </Text>
105 </View>
106 );
107};
108
109AvatarText.displayName = 'Avatar.Text';
110
111const styles = StyleSheet.create({
112 container: {
113 justifyContent: 'center',
114 alignItems: 'center',
115 },
116 text: {
117 textAlign: 'center',
118 textAlignVertical: 'center',
119 },
120});
121
122export default withTheme(AvatarText);