As farwayer mentioned you can use react hooks.
They were introduced in React 16.8, and added to React Native in version 0.59.
You will have to use both useState and useEffect.
const AnimatedComponent = (props)=>{
// Need to create state first. Setter is not used in this case
const [value] = useState(new Animated.Value(props.value))
useEffect(()=>{
Animated.timing(value, {
toValue: props.value,
duration: 100,
}).start() // < Don't forget to start!
}, [props.value]) // < Run animation only when props.value changed
// Apply animated property to your style
return (
<Animated.View style={{width: value}} />
)
}
For example this is how I implemented a progress bar:
const ProgressBar = (props)=>{
const [value] = useState(new Animated.Value(props.value))
useEffect(()=>{
Animated.timing(value, {
toValue: props.value,
duration: 100,
}).start()
}, [props.value])
const width = value.interpolate({
inputRange: [0, 100],
outputRange: ['0%', '100%'],
})
return (
<View style={{
width: '100%',
height: '100%',
flexDirection: 'row',
backgroundColor: 'white',
}}>
<Animated.View style={{
width: width,
height: '100%',
backgroundColor: 'green',
}}></Animated.View>
</View>
)
}
UPTADED