Skip to content

Instantly share code, notes, and snippets.

@sofyan-ahmad
Last active April 1, 2020 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofyan-ahmad/8dd51af35fa2656376d9e98050a37cbb to your computer and use it in GitHub Desktop.
Save sofyan-ahmad/8dd51af35fa2656376d9e98050a37cbb to your computer and use it in GitHub Desktop.
React Native Fade View Component using hook
import React, {useEffect, useRef, useState} from 'react';
import {Animated, StyleProp, ViewStyle} from 'react-native';
export interface IFadeView {
visible: boolean;
children: React.ReactNode;
style?: StyleProp<ViewStyle>;
}
export function FadeView(props: IFadeView): React.ReactElement {
const [visible, setVisible] = useState(props.visible);
const visibility = useRef(new Animated.Value(props.visible ? 1 : 0)).current;
useEffect(() => {
if (props.visible) {
setVisible(true);
}
Animated.timing(visibility, {
toValue: props.visible ? 1 : 0,
duration: 300,
useNativeDriver: false,
}).start(() => {
setVisible(props.visible);
});
}, [props.visible]);
return (
<Animated.View
style={[
visible ? props.style : {},
{
opacity: visibility.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
}),
transform: [
{
scale: visibility.interpolate({
inputRange: [0, 1],
outputRange: [1.1, 1],
}),
},
],
},
]}>
{visible ? props.children : null}
</Animated.View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment