CodeBlanks Logo Icon CodeBlanks

Modal

Learn custom dialogs with the Modal component.

The Modal component

A Modal is an overlay component that covers the entire screen. It is more flexible than Alert: you can put any components inside it; custom buttons, forms, images. Modal is part of the react-native package.

Whether the Modal is shown depends on the visible prop. When visible is true the Modal is shown, when false it is hidden. It is usually controlled with a useState variable.

Practice Your turn: show content with Modal

Add a Modal. Set its visible prop to {visible}. Inside the Modal place a <Text> and a <Button>; when pressed call setVisible(false).

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 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}>
        <View>
          <Text>Content</Text>
          <Button title="Close" onPress={() => setVisible(false)} />
        </View>
      </Modal>
    </View>
  );
}

Modal content

You can put any React Native component inside the Modal component: View, Text, TextInput, Button and more. The content stays on screen as long as the Modal is visible. When the Modal closes the content is hidden too.

You usually wrap the Modal content in a View and style it. This lets you control the content position and background. By default the Modal covers the entire screen; you can customize it with transparent and styles.

Questions and answers

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

1 Which prop controls the visibility of a Modal?

App.js
<Modal visible={true}>...</Modal>
  • open
  • visible Correct answer
  • show
  • display

Explanation: The visible prop opens and closes the Modal.

2 Fill in the blank: Modal visible prop

Question
<Modal ____={visible}>
Answer
<Modal visible={visible}>

Explanation: You control the Modal with visible.

3 Match: Modal prop and role

Term Meaning
visible visibility control
animationType open animation
transparent background transparency

All lessons in Beginner