import * as React from 'react'; import { Animated, StyleProp, StyleSheet, TextStyle } from 'react-native'; import { withTheme } from '../core/theming'; import { black, white } from '../styles/colors'; import getContrastingColor from '../utils/getContrastingColor'; import isNativeAnimationSupported from '../utils/isNativeAnimationSupported'; const defaultSize = 20; type Props = React.ComponentProps & { /** * Whether the badge is visible */ visible?: boolean; /** * Content of the `Badge`. */ children?: string | number; /** * Size of the `Badge`. */ size?: number; style?: StyleProp; ref?: React.RefObject; /** * @optional */ theme: ReactNativePaper.Theme; }; /** * Badges are small status descriptors for UI elements. * A badge consists of a small circle, typically containing a number or other short set of characters, that appears in proximity to another object. * *
*
* *
Badge with content
*
*
* *
Badge without content
*
*
* * ## Usage * ```js * import * as React from 'react'; * import { Badge } from 'react-native-paper'; * * const MyComponent = () => ( * 3 * ); * * export default MyComponent; * ``` */ const Badge = ({ children, size = defaultSize, style, theme, visible = true, ...rest }: Props) => { const { current: opacity } = React.useRef( new Animated.Value(visible ? 1 : 0) ); const isFirstRendering = React.useRef(true); const { animation: { scale }, } = theme; React.useEffect(() => { // Do not run animation on very first rendering if (isFirstRendering.current) { isFirstRendering.current = false; return; } Animated.timing(opacity, { toValue: visible ? 1 : 0, duration: 150 * scale, useNativeDriver: isNativeAnimationSupported(), }).start(); }, [visible, opacity, scale]); const { backgroundColor = theme.colors.notification, ...restStyle } = (StyleSheet.flatten(style) || {}) as TextStyle; const textColor = getContrastingColor(backgroundColor, white, black); const borderRadius = size / 2; return ( {children} ); }; export default withTheme(Badge); const styles = StyleSheet.create({ container: { alignSelf: 'flex-end', textAlign: 'center', textAlignVertical: 'center', paddingHorizontal: 4, overflow: 'hidden', }, });