CodeBlanks Logo Icon CodeBlanks

Toast

Learn toast messages.

Toast messages

A Toast is a small notification that briefly appears at the bottom of the screen. Unlike Alert it is not modal, does not block the user and disappears on its own after a few seconds. React Native provides the ToastAndroid component for Android.

Usage is simple: ToastAndroid.show(message, duration). Duration takes two values: ToastAndroid.SHORT (about 2 seconds) and ToastAndroid.LONG (about 3.5 seconds). ToastAndroid does not work on iOS; for iOS you need a library.

Toast durations

ToastAndroid has two constant duration values. ToastAndroid.SHORT shows the message for about 2 seconds; suitable for quick notifications. ToastAndroid.LONG shows it for about 3.5 seconds; preferred for longer text.

ToastAndroid.show(
  'Save successful',
  ToastAndroid.SHORT
);

You provide the duration as a constant, not a number. You must import ToastAndroid from the react-native package.

Practice Your turn: show a Toast notification

Import ToastAndroid from react-native. When a button is pressed call ToastAndroid.show('Saved', ToastAndroid.SHORT).

Starter code

App.js
import { Button } from 'react-native';

function Screen() {
  return (
    <Button
      title="Save"
      onPress={() => {
        // show a Toast notification
      }}
    />
  );
}

Sample solution

App.js
import { ToastAndroid, Button } from 'react-native';

function Screen() {
  return (
    <Button
      title="Save"
      onPress={() => ToastAndroid.show('Saved', ToastAndroid.SHORT)}
    />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match: Toast and Alert

Term Meaning
Toast auto-dismisses
Alert blocks until pressed
ToastAndroid.SHORT short duration

2 On which platform does ToastAndroid work?

App.js
ToastAndroid.show('Hello', ToastAndroid.SHORT)
  • Only iOS
  • Both iOS and Android
  • Only Android Correct answer
  • Only web

Explanation: ToastAndroid works only on Android.

3 Fill in the blank: Toast call

Question
ToastAndroid.____('Saved', ToastAndroid.SHORT);
Answer
ToastAndroid.show('Saved', ToastAndroid.SHORT);

Explanation: show displays the Toast notification.

All lessons in Beginner