Skip to content

Instantly share code, notes, and snippets.

@sofyan-ahmad

sofyan-ahmad/FadeView.tsx

Last active Apr 1, 2020
Embed
What would you like to do?
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