Creating Dialogs in React Native
Tags: reactnative
Published: 2023-03-07 00:15:39

by [Joakim Gakure](https://blog.openreplay.com/authors/joakim-gakure)

Dialogs provide a way to display modal windows and overlays in React Native components. They are used to display additional information, prompt the user for input, create additional interactions, or display messages. In this article, you will go through setting up and using dialogs in React Native.

## Setting things up

Ensure you have a working application. Run the following command to initialize a React Native application:

```bash
npx react-native init custom-dialog
```

Once the installation is complete, proceed to the newly created directory:

```bash
cd custom_dialog
```

You can test the initialized application by starting the development environment based on your platform:

```bash
#android
npm run android
#ios
npm run ios
```

## Setting up the state for the dialog

States determine a component's behavior and render information to the user. A dialog requires states to manage dialog interaction events. You will require a state to manage user interaction with a dialog component. Therefore, go to your project `src/app.js` file and import the state hook from React:

```javascript
import { useState } from 'react';
```

Inside the render function, add a state definition for dialog visibility:

```javascript
const [isVisible,setVisible] = useState(false);
```

Additionally, create a function to toggle the visibility of the dialog:

```javascript
const toggleVisibility = () => setVisible(!isVisible);
```

This state will create the logic to open and close the dialog.

## Displaying a basic dialog

You can use React Native components to create custom dialogs. Alternatively, you can utilize React Native dialog-based libraries to create dialogs. Let's use these two approaches and learn how to create dialogs. First, let's create a basic custom dialog.

You will require to import the view components from react-native. The following component will be created in the `app.js` as follows:

- Add these component elements:

```javascript
import { StyleSheet, Text, View, Modal, Button } from 'react-native';
```

- Inside the parent `View` component, add a `Button` component for triggering the dialog, i.e., **Show Dialog**:

```javascript
<Button title="Show Dialog" onPress={() => toggleVisibility()} />
```

- Beneath it, show the basic alert dialog:

```javascript
<Modal visible={isVisible} animationType="fade" transparent={true}>
    <View style={styles.modalView}>
        <View style={styles.alert}>
          <Text style={styles.alertTitle}>Attention!</Text>
          <Text style={styles.alertMessage}>Your account has been activated.</Text>
          <View style={styles.alertButtonGroup}>
            <View style={styles.alertButton}>
                <Button title="OK" onPress={() => toggleVisibility()} />
            </View>
          </View>
        </View>
    </View>
</Modal>
```

Once the button is clicked, the application will change state to visible to allow the dialog component to be displayed.

- Update the styles as follows:

```javascript
const styles = StyleSheet.create({
    container:{
        display:'flex',
        flex:1,
        justifyContent:'center',
        alignContent:'center',
        backgroundColor:'#fff'
    },
    modalContainer:{
        backgroundColor:"#ccc",
        top:0,
        left:0,
        right:0,
        bottom:0,
        position:'absolute',
    },
    modalView:{
        flex:1,
        alignContent:'center',
        justifyContent:'center'
    },
    alert:{
        width:'100%',
        maxWidth:300,
        margin:48,
        elevation:24,
        borderRadius:2,
        backgroundColor:'#fff'
    },
    alertTitle:{
        margin:24,
        fontWeight:"bold",
        fontSize:24,
        color:"#000"
    },
    alertMessage:{
        marginLeft:24,
        marginRight:24,
        marginBottom:24,
        fontSize:16,
        color:"#000"
    },
    alertButtonGroup:{
        marginTop:0,
        marginRight:0,
        marginBottom:8,
        marginLeft:24,
        padding:10,
        display:"flex",
        flexDirection:'row',
        justifyContent:"flex-end"
    },
    alertButton:{
        marginTop:12,
        marginRight:8,
        width:100
    },
});
```

This dialog is called information dialog, which just displays something to the user.

## How to close the dialog

To close the dialog, you can do that using two approaches:

- Clicking outside the dialog - To close the dialog, add the `onRequestClose` method that will execute the `toggleVisibility` state to close the dialog accordingly.
- Clicking a dialog button - You need to wrap the dialog with `TouchableOpacity` that will execute the `onPressOut` method to close the dialog.

Below is the code sample that you need to execute the above two options:

```javascript
<Modal visible={isVisible} animationType="fade" transparent={true} onRequestClose={() => toggleVisibility()}>
 <TouchableOpacity style={styles.modalContainer} onPressOut={() => toggleVisibility()}>
    <View style={styles.modalView}>
        <View style={styles.alert}>
          <Text style={styles.alertTitle}>Attention!</Text>
          <Text style={styles.alertMessage}>Your account has been activated.</Text>
          <View style={styles.alertButtonGroup}>
            <View style={styles.alertButton}>
                <Button title="OK" onPress={() => toggleVisibility()} />
            </View>
          </View>
        </View>
    </View>
  </TouchableOpacity>
</Modal>
```

Ensure that the development server is running. Once you click on the show dialog button, you should be able to see a dialog as below:

![--](https://blog.openreplay.com/images/creating-dialogs-in-react-native/images/GHwe4oh.jpg)

Note that, Once you click the OK button, the dialog visibility will change, and the dialog will be closed. Also, `onPressOut` will close the dialog container whenever you click outside the dialog container.


<h2>Session Replay for Developers</h2> 
<p><em>
Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data
</em></p>
<img alt="OpenReplay" width="768" height="400" src="https://blog.openreplay.com/assets/overview_Z17Qdyg.png" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em>




## Adding buttons for interactive elements

Let's add some interaction to the dialog based on how the user will interact with a dialog.

Note that when using dialogs, you can use icons to make your dialog more informational while remaining interactive. In that can, the following dialog will require a simple icon. You can get a thumbs-up icon from [flaticon](https://www.flaticon.com/) and save it in the project directory.

Import this icon as an image component in your `app.js`:

```javascript
import {Image} from 'react-native';
```

To use the static icon, import the image file while specifying the path using `require()`:

```javascript
const staticImage = require("./thumbs-up.png");
```

Using the above simple dialog, let's build up on it and create some interaction buttons. In the render function of the alert component, add the icon and the two buttons, CANCEL and OK:

```javascript
<View style={styles.alert}>
    <Image style={styles.alertIcon} source={staticImage} />
    <Text style={styles.alertTitle}>Attention!</Text>
    <Text style={styles.alertMessage}>To continue, You must enter your password.</Text>
    <View style={styles.alertButtonGroup}>
        <View style={styles.alertButton}>
            <Button title="Cancel" onPress={() => toggleVisibility()} />
        </View>
        <View style={styles.alertButton}>
            <Button title="OK" onPress={() => toggleVisibility()} />
        </View>
        </View>
</View>
```

Add their styles in the styles section:

```javascript
alertButtonGroup:{
    marginTop:0,
    marginRight:0,
    marginBottom:8,
    marginLeft:24,
    display:"flex",
    flexDirection:'row',
    justifyContent:"space-between"
},
alertButton:{
    marginTop:12,
    marginRight:8
},
alertIcon:{
    width:40,
    height:40,
    left:130,
    top:-20
}
```

Ensure that the development server is running. Your alert now will be as follows. Once you click the button, a log will be created based on that specific dialog button:

![--](https://blog.openreplay.com/images/creating-dialogs-in-react-native/images/zBKKPbt.jpg)

## Creating a three buttons dialog

A dialog is limited, but it can handle anything you intend to. For example, if you want to add more interaction buttons, you can do so easily. Let's create a three-button-based dialog here. In the render function of the `app.js` file, inside the dialog component, add the three buttons, Cancel, Try Another Method, and OK, as follows:

```javascript
<View style={styles.alertButtonGroup}>
    <View style={styles.alertButton}>
        <Button title="Cancel" onPress={() => console.log("Cancel Pressed")} />
    </View>
    <View style={styles.alertButton}>
        <Button title="Try Another Method" onPress={() => console.log("Try Another Method Pressed")} />
    </View>
    <View style={styles.alertButton}>
        <Button title="OK" onPress={() => console.log("OK Pressed")} />
    </View>
</View>
```

Arrange the buttons vertically by adding the style below:

```javascript
alertButtonGroup:{
    marginTop:0,
    marginRight:0,
    marginBottom:8,
    marginLeft:24,
    display:"flex",
    flexDirection:'column',
    justifyContent:"space-between"
}
```

Ensure that your development server is running. You should get the three buttons dialog as below:
 
![--](https://blog.openreplay.com/images/creating-dialogs-in-react-native/images/1e3AlXK.jpg)

## Adding a text input on the alert dialog

In the `app.js`, add an import for the TextInput component:

```javascript
import {TextInput} from 'react-native';
```

Add a state for the input:

```javascript
const [input,setInput] = useState('');
```

Inside the View for the alert, add the text input component in place of the alert message:

```javascript
<TextInput placeholder="Enter An Input" value={password} onChangeText={ (value) => setInput(value)} />
```

Beneath the modal, show the input if it is set:

```javascript
{
    input && <Text>Your input is {input}</Text>
}
```

Your render function should be similar to the following:

```javascript
return (
    <SafeAreaView style={styles.container}>
    <Button title="Show Dialog" onPress={() => toggleVisibility()} />
    <Modal visible={isVisible} animationType="fade" transparent={true} onRequestClose={() => toggleVisibility()}>
        <TouchableOpacity style={styles.modalContainer} onPressOut={() => toggleVisibility()}>
            <View style={styles.modalView}>
                <View style={styles.alert}>
                <Text style={styles.alertTitle}>Enter Your Password to Confirm</Text>
                <TextInput placeholder='Enter Your Password'secureTextEntry={true} placeholderTextColor="#000" style={styles.textInput} value={input} onChangeText={(value) => setInput(value)} />
                <View style={styles.alertButtonGroup}>
                    <View style={styles.alertButton}>
                    <Button title="Cancel" onPress={() => toggleVisibility()} />
                    </View>
                    <View style={styles.alertButton}>
                    <Button title="Try Another Method" onPress={() => toggleVisibility()} />
                    </View>
                    <View style={styles.alertButton}>
                    <Button title="OK" onPress={() => toggleVisibility()} />
                    </View>
                </View>
                </View>
            </View>
        </TouchableOpacity>
    </Modal>
    </SafeAreaView>
);
```

Add some styles for the text input:

```javascript
textInput:{
    marginLeft:24,
    marginRight:24,
    marginBottom:24,
    fontSize:16
},
```

Ensure your development server is up and running. The dialog should be able to provide a text input area as below:

![--](https://blog.openreplay.com/images/creating-dialogs-in-react-native/images/gi0G81H.jpg)

## Alternative to using custom dialog

The above examples demonstrated how to build custom dialogs. While dialogs are not limited to custom approaches, you still utilize dialog-based libraries to create your dialogs.

Here is an example of how to create React Native dialogs using [react-native-dialog](https://www.npmjs.com/package/react-native-dialog) package

Install the *react-native-dialog* package to your project:

```bash
npm install react-native-dialog
```

Import the Dialog from the package in your `app.js` file:

```javascript
import Dialog from "react-native-dialog";
```

Render the dialog based on the `isVisible` prop. Use the `Dialog` method to add the dialog elements as follows:

```javascript
<View>
    <Dialog.Container visible={isVisible}>
    <Dialog.Title>File Submit</Dialog.Title>
    <Dialog.Description>
       Confirm you want to submit this file.
    </Dialog.Description>
    <Dialog.Button label="Cancel" onPress={() => toggleVisibility()} />
    <Dialog.Button label="Delete" onPress={() => toggleVisibility()} />
    </Dialog.Container>
</View>
```

This should display the following dialog based on the above packaged based component:

![--](https://blog.openreplay.com/images/creating-dialogs-in-react-native/images/35xP8Zd.jpg)

## Conclusion

In React Native, there are several libraries available for implementing dialogs. You can use the following:

- [react-native-modal-dialog](https://www.npmjs.com/package/react-native-modal)
- [react-native-alert-notification](https://www.npmjs.com/package/react-native-alert-notification)

These libraries provide a way to create and customize dialogs easily. You can leverage React Native components for more personalized dialogs and build custom dialogs that fit your need.







[![newsletter](https://blog.openreplay.com/newsletter_Z1P0UIP.png)](https://newsletter.openreplay.com/)