Last active
April 28, 2020 23:50
-
-
Save gnardini/8619c0178d05e13078e428541f5d5e7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState, useRef } from 'react' | |
import { Animated, Easing } from 'react-native' | |
import PropTypes from 'prop-types' | |
const AnimatedNumber = ({ value, initialValue, animate, ...props }) => { | |
const [displayValue, setDisplayValue] = useState(initialValue) | |
const displayValueAnimation = useRef(new Animated.Value(initialValue)).current | |
useEffect(() => { | |
if (!animate) { | |
return | |
} | |
Animated.timing(displayValueAnimation, { | |
toValue: value, | |
duration: 1200, | |
useNativeDriver: true, | |
easing: Easing.out(Easing.quad), | |
}).start() | |
}, [value]) | |
useEffect(() => { | |
const id = displayValueAnimation.addListener(({ value }) => { | |
setDisplayValue(Math.trunc(value)) | |
}) | |
return () => { | |
displayValueAnimation.removeListener(id) | |
} | |
}) | |
return <Animated.Text {...props}>{animate ? displayValue : value}</Animated.Text> | |
} | |
AnimatedNumber.propTypes = { | |
value: PropTypes.number.isRequired, | |
initialValue: PropTypes.number, | |
animate: PropTypes.bool, | |
} | |
AnimatedNumber.defaultProps = { | |
initialValue: 0, | |
animate: true, | |
} | |
export default AnimatedNumber |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment