React Native - Modal - Mobile Application Development
Felicitations! You are standing in the right place! Today, we will show you how to utilize the modal component in React Native.
Our starting screen will look like this −
If we click the button, the modal will open -
Implementation
First, You must set up your local development environment. Follow the below link to set up your local environment.
After executing the commands mentioned in this link, a folder with a specified name is created with the following contents.
Next, we are going to edit the App.js file and write the below code.
import React from 'react';
import { TouchableOpacity, StyleSheet, Text, View, Button, Modal }
from 'react-native';
export default class App extends React.Component {
state = {
isVisible: false,
}
render() {
return (
<View style={styles.container}>
<Modal
animationType={"fade"}
transparent={false}
visible={this.state.isVisible}
onRequestClose={() => { console.log("Modal has been closed.") }}>
<View style={styles.modal}>
<Text style={styles.text}>Modal is open!</Text>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => {
this.setState({ isVisible: !this.state.isVisible })
}}>
<Text style={styles.buttonTextStyle}>
Click To Close Modal
</Text>
</TouchableOpacity>
</View>
</Modal>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => { this.setState({ isVisible: true }) }}>
<Text style={styles.buttonTextStyle}>
Click To Open Modal
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'purple',
},
modal: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: "green",
height: 350,
width: '80%',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff',
marginTop: 80,
marginLeft: 40,
},
text: {
color: 'white',
marginTop: 10
},
buttonStyle: {
backgroundColor: 'red',
borderWidth: 0,
color: 'white',
borderColor: '#51D8C7',
alignItems: 'center',
borderRadius: 5,
marginTop: 15,
padding: 10,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
});
Run
sibinmuhammed@ladmin-H310M-S2:~$ react-native start
sibinmuhammed@ladmin-H310M-S2:~/knf-reactnative/KnowledgeFactoryDemo$ react-native run-android