Issue
I am currently following the modal example given here.
https://facebook.github.io/react-native/docs/modal.html
The code works and it is indeed showing a modal box.
But there is no "close" functionality except the one via TouchableHighlight onPress event.
Is it possible to have a "close modal" functionality via "X" on the corner ?
I checked out the props and I am not able to find any.
So does this mean that using only the TouchableHighlight's onPress event alone you will be able to control the modal's closing ?
App.js code
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View } from 'react-native';
export default class ModalExample extends Component {
state = {
modalVisible: false,
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
render() {
return (
<View style={{marginTop: 22}}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {alert("Modal has been closed.")}}
>
<View style={{marginTop: 22}}>
<View>
<Text>Hello World!</Text>
<TouchableHighlight onPress={() => {
this.setModalVisible(!this.state.modalVisible)
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<TouchableHighlight onPress={() => {
this.setModalVisible(true)
}}>
<Text>Show Modal</Text>
</TouchableHighlight>
</View>
);
}
}
Solution
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View } from 'react-native';
export default class ModalExample extends Component {
state = {
modalVisible: false,
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
closeModal = () => {
this.setState({modalVisible: false})
}
render() {
return (
<View style={{marginTop: 22}}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {alert("Modal has been closed.")}}
>
<View style={{marginTop: 22}}>
<View>
<Text>Hello World!</Text>
<TouchableHighlight onPress={() => {
this.setModalVisible(!this.state.modalVisible)
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
<CloseButton onPress={this.closeModal} /> // Create your 'X' button with your preferred styling
</View>
</Modal>
<TouchableHighlight onPress={() => {
this.setModalVisible(true)
}}>
<Text>Show Modal</Text>
</TouchableHighlight>
</View>
);
}
}
You just need to add a button to the modal with your preferred styling and on the button's onPress listener set the state variable modalVisible
to false
for hiding the modal.
Answered By - Shubhnik Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.