concept ToastAndroid in category react native

This is an excerpt from Manning's book React Native in Action.
11.6 Implementing Android toasts using ToastAndroid
ToastAndroidallows you to easily call native Android toasts from a React Native application. An Android toast is a popup with a message that goes away after a given period of time (see figure 11.6). To get started building out this component, create app/Toast.js, as shown in the next listing.Listing 11.13 Implementing
ToastAndroidimport React from 'react' import { View, Text, ToastAndroid } from 'react-native' #1 let styles const Toast = () => { let { container, button } = styles const basicToast = () => { #2 ToastAndroid.show('Hello World!', ToastAndroid.LONG) #2 } const gravityToast = () => { #3 ToastAndroid.showWithGravity('Toast with Gravity!', ToastAndroid.LONG, ToastAndroid.CENTER) } return ( <View style={container}> #4 <Text style={button} onPress={basicToast}> #5 Open basic toast </Text> <Text style={button} onPress={gravityToast}> #6 Open gravity toast </Text> </View> ) } styles = { container: { flex: 1, justifyContent: 'center', alignItems: 'center' }, button: { marginBottom: 10, color: 'blue' } } export default Toast #1 Imports ToastAndroid from React Native #2 Creates a basicToast method that will call ToastAndroid.show() #3 Creates a gravityToast method that will call ToastAndroid.showWithGravity() #4 Creates two buttons in the view: Open basic toast and Open gravity toast #5 Opens the basicToast popup when the button is pressed #6 Opens the gravityToast popup when the button is pressedFigure 11.6
ToastAndroidwith toasts in the default and middle positions![]()
The
ToastAndroid.show()takes two arguments: a message and a length of time to show the toast. The time can be eitherSHORT(about 2 seconds) orLONG(about 4 seconds); this example usesLONG. TheToastAndroid.showWithGravity()method is likeToastAndroid.show(), but you can pass it a third argument to position the toast at the top, bottom, or center of the view. In this case, you’re positioning the toast in the middle of the screen withToastAndroid.CENTERas the third argument.