Created
January 31, 2022 04:13
-
-
Save martsie/a09b8192fe9ad40afc1a26ffc1c3c81c to your computer and use it in GitHub Desktop.
Reduce motion linked up to animations
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 { | |
StyleSheet, | |
Text, | |
View, | |
Animated, | |
TouchableOpacity, | |
Pressable, | |
} from 'react-native'; | |
import { useReduceMotion } from './src/hooks/useReduceMotion'; | |
export default function App() { | |
const [isOpen, setIsOpen] = useState(false); | |
const animationProgress = useRef<Animated.Value>( | |
new Animated.Value(0) | |
).current; | |
const shouldReduceMotion = useReduceMotion(); | |
const popupAnimationStyle = shouldReduceMotion | |
? { | |
opacity: animationProgress, | |
} | |
: { | |
transform: [ | |
{ | |
scale: animationProgress, | |
}, | |
], | |
}; | |
const popupOverlayAnimationStyle = { | |
opacity: animationProgress, | |
}; | |
const onClose = () => { | |
Animated.timing(animationProgress, { | |
duration: 300, | |
toValue: 0, | |
useNativeDriver: true, | |
}).start(() => { | |
setIsOpen(false); | |
}); | |
}; | |
useEffect(() => { | |
if (isOpen) { | |
Animated.timing(animationProgress, { | |
duration: 300, | |
toValue: 1, | |
useNativeDriver: true, | |
}).start(); | |
} | |
}, [isOpen]); | |
return ( | |
<View style={styles.container}> | |
<TouchableOpacity onPress={() => setIsOpen(true)}> | |
<Text>Open popup</Text> | |
</TouchableOpacity> | |
{isOpen && ( | |
<> | |
<Pressable onPress={onClose} style={StyleSheet.absoluteFill}> | |
<Animated.View | |
style={[styles.popupOverlay, popupOverlayAnimationStyle]} | |
/> | |
</Pressable> | |
<Animated.View style={[styles.popup, popupAnimationStyle]}> | |
<Text>Popup content</Text> | |
</Animated.View> | |
</> | |
)} | |
</View> | |
); | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
alignItems: 'center', | |
justifyContent: 'center', | |
}, | |
popupOverlay: { | |
backgroundColor: 'rgba(0,0,0,0.5)', | |
...StyleSheet.absoluteFillObject, | |
}, | |
popup: { | |
backgroundColor: '#ffaaaa', | |
borderRadius: 5, | |
height: 300, | |
width: '90%', | |
position: 'absolute', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment