Last active
July 22, 2020 08:20
-
-
Save MrHertal/604ed44fd2944de68b5cfe13aca9dc92 to your computer and use it in GitHub Desktop.
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 * as React from "react"; | |
import { StyleSheet, Text, View } from "react-native"; | |
import { ToastType } from "./ToastProvider"; | |
import { useToast } from "../hooks/useToast"; | |
export const Toast: React.FC = () => { | |
// Toast is using hook to retrieve config and to hide itself | |
const { toastConfig, hideToast } = useToast(); | |
React.useEffect(() => { | |
if (!toastConfig) { | |
return; | |
} | |
// Sets up a timer to hide toast after duration | |
const timer = setTimeout(hideToast, toastConfig.duration); | |
return () => clearTimeout(timer); | |
}, [toastConfig, hideToast]); | |
// When config is null, toast is hidden | |
if (!toastConfig) { | |
return null; | |
} | |
const { type, message } = toastConfig; | |
let backgroundColor; | |
switch (type) { | |
case ToastType.Info: | |
backgroundColor = 'blue'; | |
break; | |
case ToastType.Error: | |
backgroundColor = 'red'; | |
break; | |
case ToastType.Success: | |
backgroundColor = 'green'; | |
break; | |
} | |
return ( | |
<View style={styles.container}> | |
<View style={[styles.toast, { backgroundColor }]}> | |
<Text style={styles.message}>{message}</Text> | |
</View> | |
</View> | |
); | |
}; | |
const styles = StyleSheet.create({ | |
container: { | |
alignSelf: "center", | |
position: "absolute", | |
bottom: 0, // Right now toast is at the very bottom, we will solve this later | |
marginHorizontal: 20, | |
maxWidth: 480, | |
}, | |
toast: { | |
borderRadius: 6, | |
padding: 16, | |
}, | |
message: { | |
fontSize: 16, | |
textAlign: "center", | |
color: '#fff', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment