UNPKG

react-native-modern-elements

Version:

A modern, customizable UI component library for React Native

47 lines (46 loc) 1.83 kB
import React, { memo, useCallback, useEffect, useRef, useState } from "react"; import { Animated, Easing, Text } from "react-native"; const NumberCount = ({ start = 0, end, duration = 2000, style = { fontSize: 32, fontWeight: "bold" }, className, prefix = "", suffix = "", formatPrice = false, locale = "en-BD", }) => { const animatedValue = useRef(new Animated.Value(start)).current; const [displayValue, setDisplayValue] = useState(start); const lastValue = useRef(start); const startAnimation = useCallback(() => { Animated.timing(animatedValue, { toValue: end, duration, easing: Easing.out(Easing.quad), useNativeDriver: false, }).start(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [end, duration]); useEffect(() => { const listenerId = animatedValue.addListener(({ value }) => { const rounded = Math.floor(value); if (rounded !== lastValue.current) { lastValue.current = rounded; setDisplayValue(rounded); } }); startAnimation(); return () => { animatedValue.removeListener(listenerId); animatedValue.stopAnimation(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [startAnimation]); const formattedValue = formatPrice ? (() => { try { return new Intl.NumberFormat(locale || "en-BD").format(displayValue); } catch (_a) { return displayValue; } })() : displayValue; return (React.createElement(Text, Object.assign({ style: style }, { className }), prefix, formattedValue, suffix)); }; export default memo(NumberCount);