Created
October 17, 2020 03:16
-
-
Save march213/bb780a7a8a86feb2b11dce8f8a9d0f60 to your computer and use it in GitHub Desktop.
React native animation using memo
This file contains 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 Animated, { Easing } from "react-native-reanimated"; | |
import { runTiming, bInterpolate } from "react-native-redash"; | |
import { useMemoOne } from "use-memo-one"; | |
const { | |
set, | |
Value, | |
Clock, | |
useCode | |
}; | |
const MyComponent:React.FC<Props> = ({isVisible, action}) => { | |
// using useMemoOne from use-memo-one | |
const { animation, clock } = useMemoOne( | |
() => ({ | |
animation: new Value(isVisible ? 0 : 1), | |
clock: new Clock() | |
}), | |
[isVisible] | |
); | |
useCode( | |
set( | |
animation, | |
// runTiming is a helper from react-native-redash | |
runTiming(clock, animation, { | |
toValue: selected ? 1 : 0, | |
duration: 250, | |
easing: Easing.inOut(Easing.ease) | |
}) | |
), | |
[animation] | |
); | |
// interpolated value, bInterpolate is a helper from react-native-redash | |
const transY = bInterpolate(animation, -20, 0); | |
return ( | |
<TouchableOpacity onPress={action}> | |
<Animated.View | |
style={{ transform: [{ translateY: transY }] }} | |
> | |
<Text>I slide down or up based on isVisible value</Text> | |
</Animated.View> | |
</TouchableOpacity> | |
); | |
} | |
// when isVisible change, the animation is restarted and the animation value get interpolated again in the other direction, from 0 to 1, or 1 to 0 depending on the visibility flag. | |
// I hope this would help people having difficulty with functional component implementation and reanimated. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment