CodeBlanks Logo Icon CodeBlanks

Summary - Alerts

Combine Alert, Toast and Modal to write a confirmation dialog.

Summary - Alerts

In this group you learned three ways to show warnings and notifications to the user. With Alert.alert you open a modal dialog; by adding buttons you get user confirmation. With ToastAndroid you show a brief notification on Android.

With Modal you create a custom overlay covering the screen; you open and close it with visible and add a transition animation with animationType. Now let us combine these in exercises.

Practice Your turn: confirmation Alert

Call Alert.alert with title 'Delete' and message 'Are you sure?'. Add two buttons: Cancel (empty onPress) and Delete (calling del()).

Starter code

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

function Screen() {
  return (
    <Button
      title="Delete"
      onPress={() => {
        // show a two-button confirmation Alert
      }}
    />
  );
}

Sample solution

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

function Screen() {
  return (
    <Button
      title="Delete"
      onPress={() =>
        Alert.alert('Delete', 'Are you sure?', [
          { text: 'Cancel', onPress: () => {} },
          { text: 'Delete', onPress: () => del() }
        ])
      }
    />
  );
}

Practice Your turn: slide-animated Modal

Add a Modal. Set visible to {visible} and animationType to "slide". Inside place a <Text> and a close button.

Starter code

App.js
import { useState } from 'react';
import { Modal, View, Text, Button } from 'react-native';

function Screen() {
  const [visible, setVisible] = useState(false);
  return (
    <View>
      <Button title="Open" onPress={() => setVisible(true)} />
      {/* add a slide Modal */}
    </View>
  );
}

Sample solution

App.js
import { useState } from 'react';
import { Modal, View, Text, Button } from 'react-native';

function Screen() {
  const [visible, setVisible] = useState(false);
  return (
    <View>
      <Button title="Open" onPress={() => setVisible(true)} />
      <Modal visible={visible} animationType="slide">
        <View>
          <Text>Popup</Text>
          <Button title="Close" onPress={() => setVisible(false)} />
        </View>
      </Modal>
    </View>
  );
}

Questions and answers

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

1 What does the visible prop of Modal do?

App.js
<Modal visible={visible}>
  • Opens and closes the Modal Correct answer
  • Styles the Modal
  • Sets the Modal position
  • Changes the Modal size

Explanation: visible opens and closes the Modal with true/false.

2 Match: tool and usage

Term Meaning
Alert.alert modal dialog
ToastAndroid brief notification
Modal custom overlay

All lessons in Beginner