concept ToastAndroid in category react native

appears as: ToastAndroid
React Native in Action

This is an excerpt from Manning's book React Native in Action.

11.6 Implementing Android toasts using ToastAndroid

ToastAndroid allows 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 ToastAndroid
import 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 pressed

Figure 11.6 ToastAndroid with toasts in the default and middle positions

c11_06.tif

The ToastAndroid.show() takes two arguments: a message and a length of time to show the toast. The time can be either SHORT (about 2 seconds) or LONG (about 4 seconds); this example uses LONG. The ToastAndroid.showWithGravity() method is like ToastAndroid.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 with ToastAndroid.CENTER as the third argument.