Passing input state from parent to child component - react-native

I want to pass the value and setValue to Right component . I've done something but it's not working.I am typing but it's deleting immediately.I can't see even what I am typing to textinput.What is the proper way to do this ?
export const Vault = ({ navigation }: VaultStackNavigationProps<"Vault">) => {
const [value, setValue] = useState("");
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Right
setText={setValue}
value={value}
/>
),
});
}, [navigation]);
return (
//component style
);
};
const Right = ({ value, setText }) => {
const [focus, setFocus] = useState(false);
const { width } = useWindowDimensions();
const onSearch = () => {
setFocus(true);
};
const onClose = () => {
setFocus(false);
};
return (
<>
<Animated.Viewstyle={{flexDirection: "row",justifyContent: "center",alignItems: "center",width:width - 40,
}}
>
{focus && (
<TextInput
value={value}
onChangeText={(text) => setText(text)}
placeholder="Type here"
/>
)}
{value.length > 0 && (
<TouchableOpacity style={{ width: width / 9 }} onPress={onClear}>
<AntDesign name="close" size={24} color="white" />
</TouchableOpacity>
)}
</Animated.View>
{!focus && (
<TouchableOpacity onPress={onSearch} style={{ width: width / 9 }}>
<AntDesign name="search1" size={24} color="#64646E" />
</TouchableOpacity>
)}
</>
);
};

Your example code cannot be run without adding more onto it. For future reference, see how to make a minimum, reproducible example.
Anyways, here is an example of passing in the state value and setter method to a child component, which I have tested:
TestComponent.js:
import React, {useState} from "react";
import {TextInput, View, Text, SafeAreaView, StyleSheet} from "react-native";
const TestComponent = props => {
const [value, setValue] = useState("");
return (
<SafeAreaView style={styles.safeAreaView}>
<View style={styles.parent}>
<ChildComponent value={value} setValue={setValue}/>
</View>
</SafeAreaView>
);
};
const ChildComponent = props => {
const textChangeHandler = (text) => {
props.setValue(text);
};
return (
<View style={styles.child}>
<Text>Input Some Text:</Text>
<TextInput
style={styles.input}
value={props.value}
onChangeText={textChangeHandler}
/>
</View>
);
};
const styles = StyleSheet.create({
safeAreaView: {
flex: 1,
},
parent: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
child: {
flexDirection: "row",
marginHorizontal: 25,
justifyContent: "center",
alignItems: "center",
},
input:{
flex: 1,
marginHorizontal: 10,
borderWidth: 1,
borderColor: "black",
}
});
export default TestComponent;
And here is the App.js file:
import React from 'react';
import {StyleSheet, SafeAreaView} from 'react-native';
import TestComponent from "./TestComponent";
export default function App() {
return (
<SafeAreaView style={styles.safeAreaView}>
<TestComponent />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeAreaView: {
flex: 1,
}
});

Related

Looped TextInput have the copy each other

this may sound stupid for the most of you but I'm new when it comes to using API and react native. My situation is the next. From my data I try to display questions and a text field so the customer can answer and therefore I retrieve the data. But my problem is the next on when I display and try to write in the TextInput no matter how I have they will all copy what I write in which ever one I'm writing on. I don't get what I am doing wrong. I tried with looping but I can't seem to get the right answer to solve my problem. Here's my code if someone can help me.
//import liraries
import React, { Component, useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TextInput,
Picker,
} from 'react-native';
// create a component
const Get = ({ navigation }) => {
const [user, setUser] = useState();
// const [text, onChangeText] = React.useState(null);
const [selectedValue, setSelectedValue] = useState("Test");
const [text, onChangeText] = useState('');
const getUserData = async () => {
try {
let response = await fetch('https://survey-back-nmucl6ui6q-ey.a.run.app/survey/7b504f09-7a67-4f99-a402-c15a9388446c', {
headers: new Headers({
'Authorization': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTUxNTU1MjMsImlhdCI6MTY1NTA2OTExOCwic3ViIjoxfQ.eoLaDT4wP99yjC38DN2Zck2sgwXFvcRYrfzxszHkQvc',
'Content-Type': 'application/x-www-form-urlencoded'
}),
});
let json = await response.json();
console.log(json.question)
setUser(json.question);
} catch (error) {
console.error(error);
}
};
useState(() => {
getUserData();
}, []);
const renderItem = ({ item }) => {
return (
<View
style={{
borderBottomWidth: 1,
borderBottomColor: '#ccc',
padding: 5,
}}>
{item.question_type == 'text-field' ?
<View style={styles.questions}>
<Text style={styles.label}>{item.name}</Text>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={text}
placeholder="Entrez votre réponse"
/>
</View>
: <Text>Erreur</Text>}
{item.question_type == 'select' ?
<View style={styles.questions}>
<Text style={styles.label}>{item.name}</Text>
<Picker
selectedValue={selectedValue}
onValueChange={(itemValue, itemIndex) =>
setSelectedValue(itemValue)}
>
{Object.keys(item.choice).map(key =>{
return (
<Picker.Item label={key} value={key} key={key} />
)
})}
</Picker>
</View>
: <Text style={{display: 'none'}}>Erreur</Text>}
<View>
{item.question_type == 'comboboxMulti' ?
<Text style={{ fontWeight: 'bold' }}>{item.name}</Text>
: <Text style={{display: 'none'}}>Ça marche pas</Text>}
</View>
</View>
);
};
return (
<View style={styles.container}>
<FlatList
data={user}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
);
};
// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
borderRadius: 5,
marginLeft: 0,
},
label: {
textTransform: 'capitalize',
},
questions: {
justifyContent: 'center',
alignItems: 'start',
}
});
//make this component available to the app
export default Get;

Can not call newly picked date/time data from outside of function

The function DateTimePick below works well and render any date/time that user selected on screen. const date, mode, show were set state to new ones via useState all good.
Here is the problem: I expect that if I call DateTimePick.date from outside (to use this data in another function/class), I will receive DateTimePick.date for last state, i.e. the date data that just has been picked and rendered. However what I receive was DateTimePick.date for initial state which is date: new Date()
Any ideas why? Thanks
import React, {useState} from 'react';
import {View, Button, Platform, Text, TextInput, StyleSheet} from 'react-native';
import DateTimePicker from '#react-native-community/datetimepicker';
import { Icon } from 'react-native-elements';
import Moment from "moment";
export const DateTimePick = () => {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setShow(Platform.OS === 'ios');
setDate(currentDate);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const showTimepicker = () => {
showMode('time');
};
return (
<View>
<View style={styles.formRow}>
<Text style={styles.formLabel}> Date</Text>
<Text onPress={showDatepicker} style={styles.formItem} value_date={date.toDateString()} onChange = {(value_date) => this.props.setState({date: value_date})}><Icon type='font-awesome-5' name='calendar' color='#512DA8' />{' ' + Moment(date).format('DD-MMM-YYYY') }</Text>
</View>
<View style={styles.formRow}>
<Text style={styles.formLabel}> Time</Text>
<Text onPress={showTimepicker} style={styles.formItem} value_time={date.toTimeString()} onChange = {(value_time) => this.props.setState({time: value_time})}><Icon type='font-awesome-5' name='clock' color='#512DA8' /> {' ' + Moment(date).format('h:mm A') }</Text>
</View>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
);
};
//export default DateTimePick;
const styles = StyleSheet.create({
formRow: {
alignItems: 'center',
justifyContent: 'center',
flex: 1,
flexDirection: 'row',
margin: 20
},
formLabel: {
fontSize: 18,
flex: 1
},
formItem: {
flex: 1
},
modal: {
justifyContent: 'center',
margin: 20
},
modalTitle: {
fontSize: 24,
fontWeight: 'bold',
backgroundColor: '#512DA8',
textAlign: 'center',
color: 'white',
marginBottom: 20
},
modalText: {
fontSize: 18,
margin: 10
},
})

How to Choose File From Button next to input filed in the form in react native. (See image for better understanding)

I am new to react native. and I have created A form. Now in that form I want A choose file button next to the input filed. And when user click on that Choose file button. Either camera will open or gallery will open(as per user choice) and then When user click on choose file button A small image or just image name comes below the choose file button
here is my image for better understanding
here is my code
import React, {useState, Component} from 'react';
import {Picker, Text, StyleSheet, View,
TextInput, Button, KeyboardAvoidingView,
ScrollView, Alert, alert, TouchableOpacity, Dimensions,} from 'react-native';
import { StackNavigator, navigation} from "react-navigation";
import { Card, Badge, Block, } from "../components";
import { theme, mocks } from "../constants";
import DigSign from "./DigSign"
import { Ionicons } from '#expo/vector-icons';
const { height } = Dimensions.get("window");
const { width } = Dimensions.get("window");
class PickerDemo extends Component{
constructor(props) {
super(props);
this.state={
};
}
validateInputs = () => {
// if (!this.state.accountNo.trim())
if (!/[A-Z]{5}[0-9]{4}[A-Z]{1}/.test(this.state.PAN))
{
this.setState({ PANError: 'Please enter valid PAN Number' })
return;
}
if (!/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(this.state.GST))
{
this.setState({ GSTError: 'Please enter valid GST Number' })
return;
}
if (!/^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$/.test(this.state.Aadhar))
{
this.setState({ AadharError: 'Please enter valid Aadhar Number' })
return;
}
else {
Alert.alert("All fields validated")
return;
}
}
handlePAN = (text) => {
this.setState({ PANError: '' })
this.setState({ PAN: text })
}
handleGST = (text) => {
this.setState({ GSTError: '' })
this.setState({ GST: text })
}
handleAadhar = (text) => {
this.setState({ AadharError: '' })
this.setState({ Aadhar: text })
}
render(){
const offset = (Platform.OS === 'android') ? -200 : 0;
const { navigation } = this.props;
return (
<View style={{flex: 1}}>
<View style={styles.header}>
<Ionicons style={{paddingLeft:20}} name="arrow-back" size={40}
color="black" onPress={() => navigation.navigate("FormItems")} />
<Text style={{fontSize:20, paddingLeft: 70, paddingTop: 10}}>KYC Details</Text>
</View>
<KeyboardAvoidingView keyboardVerticalOffset={offset} style={styles.form} behavior='padding'>
<Text style={styles.formLabel}> OTHER INFORMATION Form </Text>
<ScrollView style={{flex: 1,}} showsVerticalScrollIndicator={false}>
<View style={{flexDirection:'row'}}>
<TextInput maxLength={30} placeholder="PAN Card Number *" style={styles.inputStyle}
onChangeText={this.handlePAN} />
<View style={{justifyContent:"center"}}>
<Button title={'Choose File'}/>
</View>
</View>
<Text>{this.state.PANError}</Text>
<View style={{flexDirection:'row'}}>
<TextInput maxLength={30} placeholder="GSTIN Number*" style={styles.inputStyle}
onChangeText={this.handleGST} />
<View style={{justifyContent:"center"}}>
<Button title={'Choose File'}/>
</View>
</View>
<Text>{this.state.GSTError}</Text>
<View style={{flexDirection:'row'}}>
<TextInput maxLength={30} placeholder="Aadhar Card Number*" style={styles.inputStyle}
onChangeText={this.handleAadhar} />
<View style={{justifyContent:"center"}}>
<Button title={'Choose File'}/>
</View>
</View>
<Text>{this.state.AadharError}</Text>
<TouchableOpacity
onPress={() => navigation.navigate("DigSign")}
>
<Card center middle shadow style={styles.category}>
<Text medium height={1} size={1}>
Digital Signature
</Text>
</Card>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigation.navigate("ImgpickWithCam")}
>
<Card center middle shadow style={styles.category}>
<Text medium height={1} size={1}>
Pick An Image From Camera
</Text>
</Card>
</TouchableOpacity>
</ScrollView>
<View style={{ height: 30 }} />
<Button style={styles.inputStyleB}
title="Submit"
color="#808080"
onPress={() => this.validateInputs()}
/>
</KeyboardAvoidingView>
</View>
);
};
}
const styles = StyleSheet.create({
form: {
flex: 1,
justifyContent: "center",
flex: 1,
backgroundColor: "rgb(247, 146, 57)",
alignItems: 'center',
paddingTop: 50,
},
container: {
flex: 1,
backgroundColor: "rgb(247, 146, 57)",
alignItems: 'center',
// justifyContent: 'center',
paddingTop: 15
},
formLabel: {
fontSize: 20,
color: 'rgb(10, 10, 10)',
},
inputStyle: {
marginTop: 20,
width: 220,
height: 40,
paddingHorizontal: 10,
borderRadius: 50,
backgroundColor: 'rgb(255, 252, 252)',
},
formText: {
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontSize: 20,
},
text: {
color: '#fff',
fontSize: 20,
},
category: {
marginTop: 20,
// this should be dynamic based on screen width
minWidth: (width - theme.sizes.padding * -10 - theme.sizes.base) / 2,
maxWidth: (width - theme.sizes.padding * -10 - theme.sizes.base) / 2,
maxHeight: (height - theme.sizes.padding * -50 - theme.sizes.base) / 2,
},
header:{
flexDirection: 'row'
}
});
export default PickerDemo;
Here is the solution based on the previous examples that I have given you.
You just had to implement the conditional rendering to it.
Just a couple of lines of code what was needed :)
Working Example: Expo Snack
import React, { useState, useEffect } from 'react';
import {
StyleSheet,
View,
Button,
Image,
FlatList,
Text,
TextInput,
} from 'react-native';
import { Camera } from 'expo-camera';
import { Ionicons } from '#expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
export default function Add() {
const [cameraPermission, setCameraPermission] = useState(null);
const [galleryPermission, setGalleryPermission] = useState(null);
const [showCamera, setShowCamera] = useState(false);
const [camera, setCamera] = useState(null);
const [imageUri, setImageUri] = useState([]);
const [type, setType] = useState(Camera.Constants.Type.back);
const [imageArray, setImageArray] = useState([]);
const permisionFunction = async () => {
// here is how you can get the camera permission
const cameraPermission = await Camera.requestPermissionsAsync();
console.log('camera permission:', cameraPermission.status);
setCameraPermission(cameraPermission.status === 'granted');
const imagePermission = await ImagePicker.getMediaLibraryPermissionsAsync();
console.log('permission:', imagePermission.status);
setGalleryPermission(imagePermission.status === 'granted');
if (
imagePermission.status !== 'granted' &&
cameraPermission.status !== 'granted'
) {
alert('Permission for media access needed.');
}
};
useEffect(() => {
permisionFunction();
}, []);
const takePicture = async () => {
if (camera) {
const data = await camera.takePictureAsync(null);
console.log(data.uri);
setImageUri(data.uri);
setImageArray([...imageArray, data.uri]);
setShowCamera(false);
}
};
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 1,
});
console.log(result.uri);
if (!result.cancelled) {
setImageArray([...imageArray, result.uri]);
}
};
return (
<View style={styles.container}>
{showCamera && (
<Camera ref={(ref) => setCamera(ref)} style={{ flex: 1 }} type={type} />
)}
{showCamera && <Button title={'Click'} onPress={takePicture} />}
{!showCamera && (
<>
<View
style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<TextInput placeholder={'Enter PAN Number'} />
<View style={{ flexDirection: 'row' }}>
<Button
title={'Camera'}
onPress={() => {
setShowCamera(true);
}}
/>
<Button title={'Gallery'} onPress={pickImage} />
</View>
</View>
{imageArray.length > 0 && (
<View style={{ height: 110 }}>
<FlatList
horizontal
data={imageArray}
renderItem={({ item }) => (
<Image
source={{ uri: item }}
style={{
width: 100,
height: 100,
borderRadius: 10,
margin: 5,
}}
/>
)}
/>
</View>
)}
</>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
marginTop: 30,
flex: 1,
},
fixedRatio: {
flex: 1,
},
});

React Native FlatList don't scroll

my FlatList doesn't scroll, I have inserted my FlatList in a SafeAreaView but doesn't work, I can see an item but I can't scroll.
How can I solve this problem?
How can I try?
Thank you
export default function App() {
const [textTodo, setTextTodo] = useState('')
const [arrayTodo, setArrayTodo] = useState([])
const inputTextHandler = (text) => {
setTextTodo(text)
}
const insertTodoHandler = () => {
if (textTodo.trim() === '') {
Alert.alert('ToDo vuoto', 'Devi inserire qualcosa da fare')
return
}
setArrayTodo([...arrayTodo, { value: textTodo, id: Math.random().toString() }])
console.log(arrayTodo)
setTextTodo('')
Keyboard.dismiss()
}
return (
<View>
<Header />
<View style={styles.container}>
<TextInput onChangeText={inputTextHandler} value={textTodo} style={styles.input} placeholder='Cosa hai da fare?' />
<Button title='INSERISCI' onPress={insertTodoHandler} />
</View>
<SafeAreaView>
<FlatList
style={styles.output}
data={arrayTodo}
renderItem={({ item }) => <Text style={styles.outputText}>{item.value}</Text>}
keyExtractor={item => item.id}
/>
</SafeAreaView>
</View>
);
}
I had tried your code it's working fine, might be a problem with your styles check this one I had tried your by changing styles:
import React, { useState} from 'react';
import { View, TextInput, ScrollView, FlatList, SafeAreaView, Button, Text, Keyboard, StyleSheet } from 'react-native';
export default function App() {
const [textTodo, setTextTodo] = useState('')
const [arrayTodo, setArrayTodo] = useState([])
const inputTextHandler = (text) => {
setTextTodo(text)
}
const insertTodoHandler = () => {
if (textTodo.trim() === '') {
Alert.alert('ToDo vuoto', 'Devi inserire qualcosa da fare')
return
}
setArrayTodo([...arrayTodo, { value: textTodo, id: Math.random().toString() }])
console.log(arrayTodo)
setTextTodo('')
}
return (
<View style={{marginTop:50,flex:1}}>
<View style={styles.container}>
<TextInput onChangeText={inputTextHandler} value={textTodo} style={styles.input} placeholder='Cosa hai da fare?' />
<Button title='INSERISCI' onPress={insertTodoHandler} />
</View>
<FlatList
style={styles.output}
data={arrayTodo}
renderItem={({ item }) => <View><Text style={styles.outputText}>{item.value}</Text></View>}
keyExtractor={item => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
padding:50,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'white',
},
input: {
borderBottomWidth: 1,
marginVertical: 15,
width: '80%',
marginHorizontal: 5,
paddingLeft: 5
},
output: {
paddingHorizontal: 50,
},
outputText: {
borderWidth: 1,
borderColor: 'grey',
padding: 10,
marginVertical: 5,
borderRadius: 10,
},
shadow: {
shadowOffset: { width: 15, height: 15 },
shadowOpacity: 1
}
});
Hope this helps!

React component not re-rendering on state change using setState

I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance
import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
popUpIsVisible: false,
};
}
setPopUpIsVisible(isVisible){
this.setState({popUpIsVisible: isVisible });
}
render() {
this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
<Text>Home Screen</Text>
<PopUpView isVisible={this.state.popUpIsVisible}/>
<Button onPress={() => {this.setPopUpIsVisible(true)}} title="Open PopUp Screen"/>
</View>
);
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
PopUpView.js
import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';
const FirstRoute = () => (
<View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
<View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
<View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
export default class PopUpView extends React.Component {
constructor(props) {
super(props);
this.state = {
modalVisible:this.props.isVisible,
index: 0,
routes: [
{ key: 'first', title: 'HIGHLIGHTS' },
{ key: 'second', title: 'AMENITIES' },
{ key: 'third', title: 'FACILITIES' },
],
};
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
renderHeader = props => <TabBar
{...props}
indicatorStyle={{backgroundColor: 'red'}}
tabStyle={styles.bubble}
labelStyle={styles.noLabel}
/>;
render() {
return (
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={styles.container}>
<View style={styles.navBar}>
<Text style={styles.navBarTitle}>Test</Text>
<TouchableOpacity
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Icon style={styles.closeButton} name="close" size={35} color="grey" />
</TouchableOpacity>
</View>
<TabView
navigationState={this.state}
renderScene={SceneMap({
first: FirstRoute,
second: SecondRoute,
third: ThirdRoute,
})}
onIndexChange={index => this.setState({ index })}
initialLayout={{ width: Dimensions.get('window').width }}
renderTabBar={props =>
<TabBar
{...props}
style={{ backgroundColor: 'white' }}
indicatorStyle={{backgroundColor: 'black'}}
tabStyle={styles.bubble}
labelStyle={styles.label}
/>
}
/>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
margin: 50,
marginLeft: 20,
marginRight: 20,
marginBottom: 20,
backgroundColor: "white",
borderWidth: 1,
borderColor: "grey",
flexDirection: 'column'
},
navBar:{
height:70,
justifyContent: 'space-between',
alignItems: 'center',
flexDirection: 'row',
borderBottomColor: 'lightgrey',
borderBottomWidth: 1,
},
navBarTitle:{
fontSize: 25,
fontFamily: 'Optima',
paddingLeft:15,
},
closeButton:{
paddingRight:12,
},
label: {
color: 'black'
}
})
The problem with your code is that you are using the state inside the PopUpView which does not change when you change the external prop. to fix this you should use the componentwillreceiveprops and update your state accordingly.
componentWillReceiveProps(nextProps){
if(this.props.isVisible!=nextProps.isVisible){
this.setState({modalVisible:nextProps.isVisible})
}
}
The better approach will be using the this.props.isVisible as the visible prop for the Model.
In this scenario you will have to pass a function as a prop to popupview which will set the popUpIsVisible to false.
Something like below
<PopUpView isVisible={this.state.popUpIsVisible}
onDismiss={()=>{this.setState({popUpIsVisible:false})}}/>
You can call the onDismiss inside the child as
<Modal visible={this.props.isVisible}>
<TouchableHighlight
onPress={() => {
this.props.onDismiss();
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</Modal>
The second approach is better as the visibility of the child is controlled by the parent.
Add below line into constructor after state defining
this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);