Skip to content

Instantly share code, notes, and snippets.

@theshane
Created February 18, 2021 20:46
Show Gist options
  • Select an option

  • Save theshane/44b9d2d77a8ec3f070195433da1bc317 to your computer and use it in GitHub Desktop.

Select an option

Save theshane/44b9d2d77a8ec3f070195433da1bc317 to your computer and use it in GitHub Desktop.
React Native Background Fade In
import React, {ReactElement, ReactNode, useEffect, useRef} from 'react';
import {
Pressable,
Animated,
Dimensions,
} from 'react-native';
export interface FadedBGProps {
testID?: string;
onPress?: () => void;
useNativeDriver?: boolean;
fadeIn?: boolean;
onFadeIn?: () => void;
onFadeOut?: () => void;
children?: ReactNode;
}
export const FadedBackground = ({
testID = 'FadedBG',
onPress = (): void => undefined,
fadeIn = true,
onFadeIn = (): void => undefined,
onFadeOut = (): void => undefined,
children,
}: FadedBGProps): ReactElement => {
// Intended to take up the whole screen
const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;
// Get an animated value ref
const fadedBGRef = useRef(new Animated.Value(0)).current;
// Interpolate --- 0 is black with 0 alpha and 1 is black with .7 alpha
// the animation library will figure out points in between
const fadedBGInerpolator = fadedBGRef.interpolate({
inputRange: [0, 1],
outputRange: ['rgba(0,0,0,0)', 'rgba(0,0,0,0.7)'],
});
// Create a fade in animation
const bgFadeInAnimation = Animated.timing(fadedBGRef, {
toValue: 1,
duration: 250,
useNativeDriver: false,
});
// Create a fade out animation
const bgFadeOutAnimation = Animated.timing(fadedBGRef, {
toValue: 0,
duration: 250,
useNativeDriver: false,
});
// Every render we look to see if we should fade in or out
useEffect(() => {
fadeIn &&
bgFadeInAnimation.start(() => {
// Ran after the fade in is complete
onFadeIn();
});
!fadeIn &&
bgFadeOutAnimation.start(() => {
// Ran after the fade out is complete
onFadeOut();
});
});
return (
<Animated.View
testID={`${testID}:AnimatedContainer`}
style={{
position: 'absolute',
bottom: 0,
width: WINDOW_WIDTH,
height: WINDOW_HEIGHT,
backgroundColor: fadedBGInerpolator, // The backgroundColor gets the interpolator instead of the actual color
}}>
<Pressable
testID={`${testID}:Pressable`}
style={{flexGrow: 1}}
onPress={onPress}
/>
{children}
</Animated.View>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment