Last active
April 1, 2020 08:25
-
-
Save sofyan-ahmad/8dd51af35fa2656376d9e98050a37cbb to your computer and use it in GitHub Desktop.
React Native Fade View Component using hook
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, 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