How to show selected value from modal on text component in react-native - react-native

How to set selected value from modal on text component in react-native.
I am using modal component from 'react-native'.
import { StyleSheet, View, Text, TouchableOpacity, Image,Modal,} from 'react-native'
<View style={styles.vwstyle}>
<Text style={styles.texthead}>You are Interested in</Text>
<View style={styles.vwside}>
<Modal
animationType="fade"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
}}>
<View style={styles.vwmodal}>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text style={styles.txtmodal}>Man</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text style={styles.txtmodal}>Woman</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text style={styles.txtmodal}>Everyone</Text>
</TouchableOpacity>
</View>
</Modal>
<TouchableOpacity
style={{flexDirection:'row'}}
onPress={() => {this.setModalVisible(true);}}>
<Text style={styles.txtselected}>Woman</Text>
<Image
source={require('../Images/rightarrow.png')} style={{ height: 20, width: 20, marginTop: 8, marginRight: 5 }} />
</TouchableOpacity>
</View>
</View>

You can use state to hold the values being pressed. I am including a code snippet here for your reference.
constructor(props) {
super(props);
this.state = {
otherStateVariables..... ,
pressedOption: ""
}
}
render() {
<View style={styles.vwstyle}>
<Text style={styles.texthead}>You are Interested in</Text>
<View style={styles.vwside}>
<Modal
animationType="fade"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
}}>
<View style={styles.vwmodal}>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
/* Add this line to set your state on onPress handler*/
this.setState({pressedOption:"Man"})
}}>
<Text style={styles.txtmodal}>Man</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
/* Add this line to set your state on onPress handler*/
this.setState({pressedOption:"Woman"})
}}>
<Text style={styles.txtmodal}>Woman</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchmodal}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
/* Add this line to set your state on onPress handler*/
this.setState({pressedOption:"Everyone"})
}}>
<Text style={styles.txtmodal}>Everyone</Text>
</TouchableOpacity>
</View>
</Modal>
<TouchableOpacity
style={{flexDirection:'row'}}
onPress={() => {this.setModalVisible(true);}}>
<Text style={styles.txtselected}>Woman</Text>
<Image
source={require('../Images/rightarrow.png')} style={{ height: 20, width: 20, marginTop: 8, marginRight: 5 }} />
</TouchableOpacity>
</View>
</View>
}
After setting the state, you can use that state variable anywhere in your code by using
this.state.pressedOption

Related

When I set State in function component I getting too many render error

UserAttemp.js
const setModal = ({ item }) => {
const perc = (item.score * 100) / item.total;
console.log("perc", perc);
if (perc >= 70) {
setImagePath(smile);
} else if (perc >= 40 && perc < 70) {
setImagePath(dis);
} else {
setImagePath(sad);
}
setTotal(item.total);
console.log("item_id",item.attempt_id);
console.log("item_total",item.total)
// setAttemp(item.attempted_question);
setScore(item.score);
setWrong(item.wrong);
setSkip(item.skip);
setModalVisible(true);
// setboolThree(false);
// setboolTwo(true);
};
const renderItem = ({ item }) => {
return (
<TouchableOpacity
style={styles.userAttemptItemContainer}
onPress={() => setModal({ item })}
>
<View>
<Text style={{alignSelf:'center',color:'black',textTransform:'uppercase'}}>{item.attempt_id}</Text>
<View
style={{ flexDirection: "row", justifyContent: "space-around" }}
>
<Text style={styles.userAttempRenderText}>Score</Text>
<Text style={styles.userAttempRenderText}>{item.score}</Text>
</View>
<Date_time
item={item}/>
</View>
</TouchableOpacity>
);
};
return (
<View>
<Loader bool={bool} />
{!bool && (
<View>
<View style={{ alignSelf: "center" }}>
<Text style={{ color: "black", fontSize: 20 }}>{title}</Text>
</View>
<FlatList
data={attempt}
renderItem={renderItem}
ListFooterComponent={<View style={{ height: 0, marginBottom: 90 }}></View>}
ListEmptyComponent={() => <EmptyListMessage />}
></FlatList>
</View>
)}
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}
>
<View style={styles.ResultModalCenterView}>
<View style={styles.ResultModalView}>
<View style={styles.ResultModalClosebuttonCon}>
<Pressable
style={[styles.ResultModalButton, styles.ResultButtonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Icon name="close" size={20} color="black" />
</Pressable>
</View>
<ModalView
score={score}
total={total}
wrong={wrong}
title={title}
skip={skipp}
attempted={attempted}
imagePath={imagePath}
/>
</View>
</View>
</Modal>
</View>
);
};
export default UserAttemps;
Date_time.js
import React, { useState } from 'react'
import { View,Text } from 'react-native';
const Date_time=(props)=> {
const [dateBool,setDateBool]=useState(props.item?false:true);
const [timeBool,setTimeBool]=useState(props.item?false:true);
if(props.item.start_date==props.item.end_date){
setDateBool(true);
}
if(props.item.start_time==props.item.end_time){
setTimeBool(true);
}
return (
<View>
{dateBool&&<View style={{flexDirection:'row',justifyContent:'center',}}>
<Text style={{color:'black',}}>Date:</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.start_date}</Text>
</View>}
{!dateBool&&<View style={{flexDirection:'row',justifyContent:'center',}}>
<Text style={{color:'black',}}>Date:</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.start_date}</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.end_date}</Text>
</View>}
{/* <View style={{flexDirection:'row',justifyContent:'center'}}>
<Text style={{color:'black'}}>Date</Text>
<Text style={{color:'black'}}>{Date}</Text>
</View> */}
{ timeBool&& <View style={{flexDirection:'row',justifyContent:'center',}}>
<Text style={{color:'black',}}>Time:</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.start_time}</Text>
</View>}
{timeBool&&<View style={{flexDirection:'row',justifyContent:'center',}}>
<Text style={{color:'black',}}>Time:</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.start_time}</Text>
<Text style={{color:'black',marginLeft:5}}>{props.item.end_time}</Text>
</View>}
</View>
)
}
export default Date_time;
I am calling component in UserAttemp.js
I have made a component of Date_time in that I am trying to set state in the body of function component but i am getting too manay render error due to the useState hook
I want to set State in the body of function Date_time.jjs component how to set?
Updating state outside the return function, makes it go in infinite loop. It will check the condition and update the state which will cause re-render then if will again check the condition and so on... it keeps re-rendering.
Remove the if statements and handle them in initial value of useState hook. Like-
const [dateBool,setDateBool]=useState(props.item?.start_date==props.item?.end_date ? true : props.item? false :true);
const [timeBool,setTimeBool]=useState(props.item?.start_time==props.item?.end_time ? true : props.item ? false:true);

react native: modal is not displaying

I am new to react-native and I am trying to display modal in react-native with following code
<View>
<View onPress={() => {this.toggleModal(true) }} onBackdropPress={ () =>
{this.hideModal(false)}}>
<View>
<OcticonsIcons name='plus' size={19}/>
<Text>QUICK ACTION</Text>
</View>
<View>
<View>
<Image source={require('../images/truck.png')}
/>
<Image source={require('../images/taxi(1).png')}
/>
<Image source={require('../images/tour.png')}
/>
</View>
</View>
</View>
</View>
<Modal visible={this.state.isModalVisible} animationType = "slide" transparent =
{false}>
<View style={{ flex: 1 }}>
<Text style={{ fontWeight:'bold', fontSize: 20, color: '#f79334', marginTop: 15
}} > Services </Text>
</View>
</Modal>
toggleModal(visible){
this.setState({ isModalVisible: visible });
}
hideModal(visible){
this.setState({ isModalVisible: visible })
}
but it's not working, can anyone tell me what wrong with my code, thank you.
The thing is you cant have onPress function on components, its solely for just showing. To use onPress you have to use TouchableOpacity.
Check the code below :
<View>
<TouchableOpacity onPress={() => {this.toggleModal(true) }} onBackdropPress={ () =>
{this.hideModal(false)}}>
<View>
<OcticonsIcons name='plus' size={19}/>
<Text>QUICK ACTION</Text>
</View>
<View>
<View>
<Image source={require('../images/truck.png')}
/>
<Image source={require('../images/taxi(1).png')}
/>
<Image source={require('../images/tour.png')}
/>
</View>
</View>
</TouchableOpacity>
</View>
<Modal visible={this.state.isModalVisible} animationType = "slide" transparent =
{false}>
<View style={{ flex: 1 }}>
<Text style={{ fontWeight:'bold', fontSize: 20, color: '#f79334', marginTop: 15
}} > Services </Text>
</View>
</Modal>
toggleModal = (visible) =>{
this.setState({ isModalVisible: visible });
}
hideModal = (visible) => {
this.setState({ isModalVisible: visible })
}
Hope it helps. feel free for doubts

undefined is not a function(evaluating '_this2.AlertButton()')?

I create touchableopacity for every item in map. it works well but when I give function to TouchableOpacity like below, it gives me error which is on title. How can I fix this ?
it gives error when I write this.AlertButton()
{section.subcategory.map((item, key) => (
<View key={key} style={styles.item}>
<TouchableOpacity
onPress={() =>this.AlertButton()}>
</TouchableOpacity>
<View style={styles.separator} />
</View>
))}
This is my alert function :
AlertButton() {
const number = 'TelNo';
Alert.alert(
'',
'Test',
[
{text: 'NO'},
{text: 'Yes', onPress: () => Linking.openURL(`tel:${number}`)},
],
);
}
Here is render. And my map function which is above is in renderContent
render() {
CONTENT2 =[];
CONTENT2 = this.state.fromPage1;
return (
<View style={styles.container}>
<View style={{height: this.state.yuksek, width: this.state.genis, justifyContent: 'center', alignItems: 'center',position:'absolute'}}>
<Text style={{fontWeight: 'bold', color:'#856F6F'}}>Yukarıdaki menü butonlarına tıklayınız.</Text>
</View>
<View style={{height: this.state.yuksek2, width: this.state.genis2, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{fontWeight: 'bold', color:'#856F6F'}}>String</Text>
</View>
<ScrollView contentContainerStyle={{}}>
<Accordion
activeSections={this.state.activeSections}
sections={CONTENT2}
touchableComponent={TouchableOpacity}
expandMultiple={false}
renderHeader={this.renderHeader}
renderContent={this.renderContent}
duration={400}
onChange={this.setSections}
/>
</ScrollView>
<View style={{height:85, width:85,position:'absolute',bottom:5,right:5}}>
<TouchableOpacity style={{flex:1}} onPress={() => this.AlertButton()}>
<ImageBackground source={require('../../image/phoneCall.png')} style={{flex:1}}>
</ImageBackground>
</TouchableOpacity>
</View>
</View>
);
}
}
just change the following line
renderContent={this.renderContent}
to
renderContent={this.renderContent.bind(this)}
because when you are using the class method directly as callback then its not definitely bound to its class when called from inside the component

React-Native modal does not open

I am trying to open the modal through a TouchableOpacity (the second line). I got it to work on a clean application, but when I basically copy and paste to a my current application it does not open at all... Another important point is that this is a card component that is within react-native-deck-swiper. That is my guess for why is won't work.
Top part of my code:
constructor() {
super();
this.state = {
modalVisible: false
}
}
setModalVisible = (visible) => {
this.setState({modalVisible: visible})
}
Bottom Part of my code with the modal
<View style={{flex: 1, justifyContent: 'flex-end', paddingLeft: 5, paddingTop: 10}}>
<TouchableOpacity onPress={() => { this.setModalVisible(true)}}>
<Icon name="more" style={{fontSize: 40}} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
<View style={{padding: 5}}>
<Text style={{fontSize: 20}}>10 miles away</Text>
</View>
<View style={{marginTop: 22, flex:1}}>
<Modal
animationType="slide"
transparent={true}
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>
</View>
You need to bind you function in the constructor or use arrow functions or else this wont be pointing to your component:
setModalVisible = (visible) => {
this.setState({modalVisible: visible})
}
According to your code, don't use the Arrow function. if you want arrow function then bind it, otherwise use below function.
setModalVisible(visible) {
this.setState({modalVisible: visible});
}

onPress not working in nested views

I'm using TouchableOpacity for handling clicks.Everything is working fine in upper hierarchy views, but bellow two containers view is not clickable.I've set an alert when it's clicked for testing purposes.View bellow comment is not working and I think it's because of bad nesting.
Here is code :
return (
<View style={styles.container}>
<View style={styles.subContainer}>
<Text style={[styles.storyLikesAndShares, { marginRight: 17 }]}>
{this.state.likes} Likes
</Text>
<Text style={styles.storyLikesAndShares}>
{this.props.story.Shares ? this.props.story.Shares : 0} Shares
</Text>
</View>
<View style={[styles.subContainer, { paddingTop: 16 }]}>
<View style={styles.storyIconsContainer}>
<TouchableOpacity onPress={() => this.changeLikedState(this.props)}>
<Icon
style={[
this.props.story && this.state.isLiked
? styles.storyLikedIcon
: styles.storyNotLikedIcon,
{ marginRight: 24 }
]}
name={"heart"}
size={24}
/>
</TouchableOpacity>
<Icon style={styles.storyNotLikedIcon} name={"share"} size={24} />
//Code bellow is not working
<TouchableOpacity
onPress={() => alert('alertiiiing')}
>
{this.props.storyViewType === "feed" ? (
<Text
onPress={() => console.log('read more clicked')}
style={styles.storyReadMoreText}>Read Full Story...</Text>
) : (
<View />
)}
</TouchableOpacity>
</View>
</View>
</View>
);
}
}