Last active
December 16, 2018 15:37
-
-
Save bvaughn/b590a6bfe9ae06fd100dea2a77ab3775 to your computer and use it in GitHub Desktop.
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 React, {useEffect, useRef, useState} from 'react'; | |
import {Animated, Text} from 'react-native'; | |
// Begin https://unpkg.com/react-native-animation-hooks@1.0.1/build/AnimationHooks.js | |
export const useAnimatedValue = initialValue => { | |
const ref = useRef(new Animated.Value(initialValue)); | |
return ref.current; | |
}; | |
const getInitialValue = config => { | |
if (typeof config.initialValue !== 'undefined') return config.initialValue; | |
else { | |
return config.toValue; // TODO deal with other types possibilities here | |
} | |
}; | |
const getAnimationType = config => config.type || 'timing'; | |
export const useAnimation = config => { | |
const animatedValue = useAnimatedValue(getInitialValue(config)); | |
const animate = () => { | |
if (config.type === 'timing') { | |
Animated.timing(animatedValue, config).start(); | |
} else if (config.type === 'spring') { | |
Animated.spring(animatedValue, config).start(); | |
} else { | |
// @ts-ignore | |
throw new Error('unsupported animation type=' + config.type); | |
} | |
}; | |
// Currently useEffect is buggy, see https://github.com/facebook/react-native/issues/21967 | |
useEffect(animate, [config.toValue]); | |
return animatedValue; | |
}; | |
// End https://unpkg.com/react-native-animation-hooks@1.0.1/build/AnimationHooks.js | |
export default function Playground() { | |
const [bool, setBool] = useState(false); | |
const toggle = () => setBool(!bool); | |
const animatedOpacity = useAnimation({ | |
toValue: bool ? 1 : 0.5, | |
type: 'timing', | |
}); | |
return ( | |
<Animated.View style={{opacity: animatedOpacity, padding: 50}}> | |
<Text onTouchEnd={toggle}>Opacity should be {bool ? 1 : 0.5}</Text> | |
</Animated.View> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment