React Native Modal With Close Button Example Tutorial

React Native

Nicesnippets

21-12-2021


React Native Modal With Close Button Example Tutorial

Hi Guys,

In this blog, I will learn you how to create modal with close button in react native. I will install step by step modal with close button in react native. We will show react native modal with close button and use icons

Here, I will give you full example for simply display modal with close button react native as bellow.

Step 1 - Create project


In the first step Run the following command for create project.

expo init odalExample

Step 2 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";

import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";

class App extends Component {

state = {

modalVisible: false

};

setModalVisible = (visible) => {

this.setState({ modalVisible: visible });

}

render() {

const { modalVisible } = this.state;

return (

<View style={styles.centeredView}>

<Modal

animationType="slide"

transparent={true}

visible={modalVisible}

style={styles.modelBox}

onRequestClose={() => {

Alert.alert("Modal has been closed.");

this.setModalVisible(!modalVisible);

}}

>

<View style={styles.centeredView}>

<View style={styles.modalView}>

<Text style={styles.modalText}>Hello World!</Text>

<Pressable

style={[styles.button, styles.buttonClose]}

onPress={() => this.setModalVisible(!modalVisible)}

>

<Text style={styles.textStyle}>Hide Modal</Text>

</Pressable>

</View>

</View>

</Modal>

<Pressable

style={[styles.button, styles.buttonOpen]}

onPress={() => this.setModalVisible(true)}

>

<Text style={styles.textStyle}>Show Modal</Text>

</Pressable>

</View>

);

}

}

const styles = StyleSheet.create({

centeredView: {

flex: 1,

justifyContent: "center",

alignItems: "center",

marginTop: 22

},

modalView: {

margin: 20,

backgroundColor: "white",

borderRadius: 20,

padding: 35,

alignItems: "center",

shadowColor: "#000",

shadowOffset: {

width: 0,

height: 2

},

shadowOpacity: 0.25,

shadowRadius: 4,

elevation: 5

},

button: {

borderRadius: 20,

padding: 10,

elevation: 2

},

buttonOpen: {

backgroundColor: "#ffb606",

},

buttonClose: {

backgroundColor: "#2196F3",

},

textStyle: {

color: "white",

fontWeight: "bold",

textAlign: "center"

},

modalText: {

marginBottom: 15,

textAlign: "center"

},

modelBox:{

backgroundColor:'rgba(52, 52, 52, 0.8)',

}

});

export default App;

Step 3 - Run project

In the last step run your project using bellow command.

npm start

Output

It will help you...


Recommended Posts