Skip to content

Instantly share code, notes, and snippets.

@gnardini
Last active April 28, 2020 23:50
Show Gist options
  • Save gnardini/8619c0178d05e13078e428541f5d5e7e to your computer and use it in GitHub Desktop.
Save gnardini/8619c0178d05e13078e428541f5d5e7e to your computer and use it in GitHub Desktop.
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