React Native - UseEffect and other functions takes time to load - reactjs

I am using React Native to create an app. My useEffect and other functions takes around a minute to call which caused delay and reduce user experience.
useEffect(() => {
const token = JWTToken('');
getAllChannels(token);
}, [navigation]);
// code to add channel
const clickSave = () => {
const token = JWTToken('');
addchannel(token);
};
// Render code
return (
<KeyboardAvoidingView
style={{
display: 'flex',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
<SafeAreaView
style={{
flex: 1,
backgroundColor: !darkTheme
? Colors.light.f2Color
: Colors.dark.backgrounColor,
}}>
<TouchableOpacity onPress={goBack}>
<View
style={{
flexDirection: 'row',
marginHorizontal: width * 0.02,
marginVertical: height * 0.02,
alignItems: 'center',
}}>
<SvgLeftArrow
color={!darkTheme ? Colors.light.textColor : Colors.light.white}
/>
<Text
style={{
fontFamily: 'OpenSans-Bold',
fontSize: 20,
color: !darkTheme ? Colors.light.textColor : Colors.light.white,
marginLeft: width * 0.03,
fontWeight: 'bold',
}}>
Manage Channels
</Text>
</View>
</TouchableOpacity>
<View
style={{
width: width * 0.95,
height: Platform.OS === 'android' ? height * 0.06 : height * 0.05,
marginVertical: height * 0.01,
backgroundColor: !darkTheme
? Colors.light.white
: Colors.dark.changePwdText,
marginHorizontal: Platform.OS === 'android' && height * 0.01,
borderRadius: 13,
alignSelf: 'center',
flexDirection: 'row',
alignItems: 'center',
}}>
<TextInput
style={{
fontSize: 16,
fontFamily: 'OpenSans-Regular',
paddingHorizontal: width * 0.04,
color: !darkTheme
? Colors.light.textColor
: Colors.dark.textColor,
width: width * 0.86,
}}
value={searchChannel}
onChangeText={value => {
setSearchChannel(value);
}}
clearButtonMode="always"
secureTextEntry={false}
placeholder="Add a channel..."
placeholderTextColor={
!darkTheme ? Colors.light.placeholderColor : Colors.dark.textColor
}
/>
{!createLoader ? (
<TouchableOpacity onPress={clickSave}>
<Image
source={require('../assets/images/black-round-tick.png')}
resizeMode="contain"
/>
</TouchableOpacity>
) : (
<ActivityIndicator color={Colors.light.black} />
)}
</View>
{!loader ? (
<FlatList
data={channelList}
scrollEnabled={true}
renderItem={({item, index}) =>
channelList.length > 0 ? (
<ChannelComponent
item={item}
setCallGetChannel={setCallGetChannel}
/>
) : (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
}}>
<Text>No Channels Found!</Text>
</View>
)
}
numColumns={1}
keyExtractor={(item, index) => index}
contentContainerStyle={{
alignSelf: 'center',
flex: 1,
}}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
onEndReachedThreshold={0}
bounces={false}
style={{marginBottom: height * 0.05}}
/>
) : (
<View
style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator color={Colors.light.black} />
</View>
)}
</SafeAreaView>
</KeyboardAvoidingView>
);
I have created as above but each function takes time to call. Even Loader shows after a minute. This is happening in my complete code. Even TouchableOpacity is also taking multiple attempts to perform.
Please suggest if you have answer for my problem.

Probably you have infinity loop here:
useEffect(() => {
const token = JWTToken('');
getAllChannels(token);
}, [navigation]);
You need to control your effect more precisely. For example, you can add condition inside your effect like:
useEffect(() => {
if (!isLoading) {
const token = JWTToken('');
getAllChannels(token);
}
}, [isLoading]);
Another way is to check how many rerenders do you have with this plugin https://github.com/welldone-software/why-did-you-render or with Flipper

Related

How to decrease and increase the height of a specific view by onpress on view in flatlist of react native?

i have rendered 10 views by using flatlist 1st i want to show the details by incresing the height when a user click on view no 6 and decrease height when user again click on it i have done it but problem is that when i click the view no 6 the height of all the views increases and render the list again from 1st view not from 6th how to increase and decrease the height of a specific view and renders from the same view which is increased
const setFunctionality = () => {
setcount(count + 1)
if (count % 2 == 0) {
setinitialHeight(windowWidth > windowHeight ? verticalScale(140) : verticalScale(150))
setIsViewShown(false)
}
else {
setinitialHeight(windowWidth > windowHeight ? verticalScale(170) : verticalScale(280))
setIsViewShown(true)
}
}
<View>
<FlatList
data={data}
// keyExtractor={(item) => item.key}
style={{ backgroundColor: '#fff', }}
contentContainerStyle={{ paddingBottom: '5%' }}
renderItem={(element) => {
return (
<View style={{ flexDirection: 'column', flex: 1, width: '100%' }}>
<TouchableOpacity onPress={() => setFunctionality()}>
<View style={{ paddingLeft: 5, flexDirection: 'row', flex: 1, height: initialHeight, backgroundColor: element.item.Status == 'Open' ? '#B7E6E6' : '#EFA5A5', marginTop: 10, borderRadius: 5, alignContent: 'center', marginHorizontal: 10, }}>
<View style={{ backgroundColor: '#fff', width: 50, height: 50, borderRadius: 27, alignSelf: 'center', justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ color: element.item.Status == 'Open' ? '#B7E6E6' : '#EFA5A5' }}>{element.item.Status}</Text>
</View>
<View style={{ flex: 1, borderTopRightRadius: 20, borderBottomRightRadius: 20, padding: windowWidth > windowHeight ? moderateScale(10) : moderateScale(15), justifyContent: 'center' }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5), marginTop: 10 }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(14) : moderateScale(12), fontFamily: 'DMSans-Bold' }}>Customer ID: {element.item.CusId}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(14) : moderateScale(12), fontFamily: 'DMSans-Bold' }}>Customer PO: {element.item.CusPo}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5) }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Date From: {element.item.Datefrm}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Date To: {element.item.Dateto}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5) }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Tracking No: {element.item.TrNo}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular' }}>Mark For: {element.item.Markfr}</Text>
</View>
{isViewShown == true ?
<View >
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5) }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Item ID: {element.item.ItmId}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Warehouse: {element.item.Wearh}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5) }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Unit Price: {element.item.UPri}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular' }}>Ext Price: {element.item.EPri}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: windowWidth > windowHeight ? verticalScale(5) : verticalScale(5) }}>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular', }}>Order No: {element.item.OrdNum}</Text>
<Text style={{ color: 'black', fontSize: windowWidth > windowHeight ? moderateScale(13) : moderateScale(12), fontFamily: 'DMSans-Regular' }}>Status: {element.item.Status}</Text>
</View>
</View>
:
null
}
</View>
</View>
</TouchableOpacity>
</View>
)
}}
/>
</View>
You need to take one state variable which stores the id of the currently selected item and with isViewShown==true? you need to do this also isViewShown==true&&selectedId==element.item.key?
for this, in your data there should be a unique id.
so on <TouchableOpacity onPress={() => setFunctionality(element.item)}>
const [selectedId,setSelectedId] = useState(null);
and in function
const setFunctionality = (item) => {
setSelectedId(item.key)
setcount(count + 1)
if (count % 2 == 0) {
setinitialHeight(windowWidth > windowHeight ? verticalScale(140) : verticalScale(150))
setIsViewShown(false)
}
else {
setinitialHeight(windowWidth > windowHeight ? verticalScale(170) : verticalScale(280))
setIsViewShown(true)
}
}
For the issue you given you need to add a condition on height also based on selectedId:
height:selectedId==element.item.id? initialHeight:20,
here instead of 20 you can take whatever initial height or normal height you want
You can use the index to identify cards.
const [selectedCardIndex,setSelectedCardIndex] = useState(null);
return(<View>
<FlatList
data={data}
style={{ backgroundColor: '#fff', }}
contentContainerStyle={{ paddingBottom: '5%' }}
renderItem={{item,index} => {
return (<TouchableOpacity
style={{height:index==selectedCardIndex?100:50}}
onPress={() => selectedCardIndex(index)}>
...your code...
</TouchableOpacity>)
})
/>
Note: But In flatlist every card should contain the same height and width.
Instead of that you can use scrollView.

React Native - Each action takes lot of time to perform

I have created a Login Page in my app like always. I created and when I click on Login button it takes around 30 seconds for loader to appear and meanwhile my button get hanged and blank. I don't know why my code is behaving like this.
Validate Login when click login button and show loader on button but it takes around 30 minutes
const validateLogin = () => {
console.log('validate login');
setLoader(true);
if (userName.length === 0 || password.length === 0) {
setLoader(false);
Alert.alert('Username or password cannot be empty.');
} else {
if (!netInfo.isConnected) {
setLoader(false);
Alert.alert('You are not connected to internet. Please try again.');
} else {
const token = JWTToken(userName);
getUser(token);
}
}
};
API Code
const getUser = JWTToken => {
console.log('get use');
var axios = require('axios');
var data = JSON.stringify({
username: userName.toLocaleLowerCase(),
password: password,
});
console.log('signin ', data);
var config = {
method: 'post',
url: BASE_URL + GET_USER,
headers: {
'x-jwt-token': JWTToken,
'Content-Type': 'application/json',
},
data: data,
};
axios(config)
.then(function (response) {
const res = JSON.stringify(response.data);
UI Code
<KeyboardAvoidingView
style={{
display: 'flex',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
<SafeAreaView
style={{
flex: 1,
backgroundColor: !darkTheme
? Colors.light.backgrounColor
: Colors.dark.backgrounColor,
justifyContent: 'center',
alignItems: 'center',
}}>
<View
style={{flex: 0.2, alignItems: 'center', justifyContent: 'center'}}>
{!darkTheme ? (
<Image
source={require('../assets/images/logo.png')}
resizeMode="contain"
/>
) : (
<Image
source={require('../assets/images/logo-white.png')}
resizeMode="contain"
/>
)}
</View>
<View
style={{
alignSelf: 'center',
justifyContent: 'center',
flex: 0.7,
width: width * 0.9,
borderRadius: 20,
backgroundColor: Colors.backgroundColor,
marginHorizontal: width * 0.03,
marginBottom: height * 0.05,
padding: width * 0.03,
marginTop: height * 0.02,
}}>
<Text
style={{
color: !darkTheme
? Colors.light.textColor
: Colors.dark.textColor,
fontFamily: 'FiraSans-Medium',
fontSize: 20,
}}>
{strings.login}
</Text>
{/* Email */}
<View
style={{
flexDirection: 'row',
marginTop: height * 0.02,
width: width,
alignItems: 'center',
}}>
{!darkTheme ? (
<Image
source={require('../assets/images/email.png')}
resizeMode="contain"
/>
) : (
<Image
source={require('../assets/images/email-white.png')}
resizeMode="contain"
/>
)}
<TextInput
style={{
fontSize: 16,
fontFamily: 'OpenSans-Regular',
paddingHorizontal: width * 0.01,
color: !darkTheme ? Colors.light.black : Colors.light.white,
borderColor: !darkTheme
? Colors.light.textInputLine
: Colors.dark.white,
borderBottomWidth: 1,
width: width * 0.7,
}}
value={userName}
onChangeText={value => {
setUserName(value);
}}
// onSubmitEditing={() => onEmailSubmit()}
clearButtonMode="always"
multiline={false}
placeholder={'Username'}
placeholderTextColor={
!darkTheme ? Colors.light.black65 : Colors.light.white65
}
autoCapitalize="none"
/>
</View>
{/* Password */}
<View
style={{
flexDirection: 'row',
marginTop: height * 0.04,
width: width,
alignItems: 'center',
}}>
{!darkTheme ? (
<Image
source={require('../assets/images/password.png')}
resizeMode="contain"
/>
) : (
<Image
source={require('../assets/images/password-white.png')}
resizeMode="contain"
/>
)}
<TextInput
style={{
fontSize: 16,
fontFamily: 'OpenSans-Regular',
paddingHorizontal: width * 0.01,
color: !darkTheme ? Colors.light.black : Colors.light.white,
borderColor: !darkTheme
? Colors.light.textInputLine
: Colors.light.white,
borderBottomWidth: 1,
width: width * 0.65,
}}
value={password}
onChangeText={value => {
setPassword(value);
}}
onSubmitEditing={() => checkPassword(password)}
secureTextEntry={securePwd}
placeholder={strings.password}
placeholderTextColor={
!darkTheme ? Colors.light.black65 : Colors.light.white65
}
autoCapitalize="none"
/>
<TouchableOpacity onPress={() => setSecurePwd(!securePwd)}>
{securePwd ? (
!darkTheme ? (
<Image
source={require('../assets/images/eye-close.png')}
resizeMode="contain"
style={{width: 30, height: 20}}
/>
) : (
<Image
source={require('../assets/images/eye-close-white.png')}
resizeMode="contain"
style={{width: 30, height: 20}}
/>
)
) : !darkTheme ? (
<Image
source={require('../assets/images/eye-open.png')}
resizeMode="contain"
style={{width: 30, height: 20}}
/>
) : (
<Image
source={require('../assets/images/eye-open-white.png')}
resizeMode="contain"
style={{width: 30, height: 20}}
/>
)}
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row-reverse'}}>
<TouchableOpacity onPress={goToForgotPwd}>
<Text
style={{
color: Colors.light.blueColor,
fontFamily: 'OpenSans-Regular',
fontSize: 16,
marginRight: width * 0.03,
marginTop: height * 0.005,
}}>
{strings.forgotPassword}
</Text>
</TouchableOpacity>
</View>
{/* sign Up button */}
<View
style={{
width: width * 0.3,
height: height * 0.05,
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 25,
marginTop: height * 0.07,
backgroundColor: Colors.light.buttonBackground,
}}>
<TouchableOpacity onPress={validateLogin}>
<View>
{!loader ? (
<Text
style={{
color: Colors.light.white,
fontFamily: 'FiraSans-Regular',
fontSize: 17,
}}>
{strings.login}
</Text>
) : (
<ActivityIndicator color={Colors.light.white} />
)}
</View>
</TouchableOpacity>
</View>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{
fontFamily: 'OpenSans-Regular',
fontSize: 16,
color: !darkTheme
? Colors.light.placeholderColor
: Colors.light.white,
marginRight: width * 0.01,
}}>
{strings.noSignUp}
</Text>
<TouchableOpacity onPress={goToRegister}>
<Text
style={{
fontFamily: 'OpenSans-Regular',
fontSize: 16,
color: Colors.light.blueColor,
}}>
{strings.register}
</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
Please help as I am not able to understand why I am having this issue.

Keyboard closed on click on button in react native

I have creating a comment modal in which user can add comment. This section has a list of comments and a text input field to enter comments and a button to submit comment but the problem is the I enter something in text input and then press button to submit comment but first time it closes the keyboard and then I need to press button again to add the text into the array.
My problem is why I need to press two times. Why on first time my keyboard got closed.
<KeyboardAvoidingView
style={{
display: "flex",
height: Dimensions.get("window").height,
width: Dimensions.get("window").width,
}}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<SafeAreaView
style={{
backgroundColor: "transparent",
flex: 1,
}}
>
<View
style={{ flex: 0.4, backgroundColor: "#000", opacity: 0.2 }}
></View>
<View
style={{
flex: 0.6,
backgroundColor: Colors.dark.text,
borderRadius: 20,
}}
>
<View
style={{
flexDirection: "row",
marginTop: "3%",
paddingVertical: height * 0.005,
marginVertical: "4%",
borderTopRightRadius: 10,
borderTopLeftRadius: 10,
paddingHorizontal: "3%",
}}
>
<View style={{ flexDirection: "column", width: width * 0.8 }}>
<Text
style={{
fontFamily: "Roboto_700Bold",
fontSize: 10,
color: Colors.light.text,
opacity: 0.4,
}}
>
COMMENTS
</Text>
<Text
style={{
fontFamily: "Roboto_700Bold",
fontSize: 20,
marginTop: height * 0.01,
}}
>
{title}
</Text>
</View>
<TouchableOpacity
onPress={() => setCommentVisible(false)}
style={{
width: width * 0.15,
alignItems: "center",
justifyContent: "center",
}}
>
<SvgRedCross />
</TouchableOpacity>
</View>
<View
style={{
flex: 0.002,
backgroundColor: Colors.light.postText,
opacity: 0.2,
}}
>
<Text></Text>
</View>
<View style={{ flex: 0.87 }}>
<FlatList
data={allComment}
showsVerticalScrollIndicator={false}
keyExtractor={(item, index) => item.id}
key={(item, index) => item.qId}
renderItem={({ item, index }) => (
<View>
<View style={{ flexDirection: "column", padding: "3%" }}>
<Text
style={{
color: "#151617",
fontFamily: "Roboto_700Bold",
fontSize: 14,
}}
>
{item.name}{" "}
</Text>
<Text
style={{
color: "#151617",
fontFamily: "Roboto_400Regular",
fontSize: 13,
}}
>
{item.comment}{" "}
</Text>
</View>
<View
style={{
height: 0.5,
backgroundColor: Colors.light.postText,
opacity: 0.2,
marginTop: "3%",
}}
>
<Text></Text>
</View>
</View>
)}
style={{}}
pagingEnabled={false}
showsHorizontalScrollIndicator={false}
/>
</View>
<View
style={{
height: height * 0.08,
elevation: 2,
backgroundColor: "#fff",
flexDirection: "row",
alignItems: "center",
borderColor: Colors.light.tabSelection,
shadowColor: Colors.light.tabSelection,
shadowOffset: {
width: 0,
height: -3,
},
shadowRadius: 1,
shadowOpacity: 0.4,
position: "absolute",
bottom: 0,
flex: 0.2,
}}
>
<TextInput
style={{
fontWeight: "300",
fontStyle: "normal",
fontSize: 13,
fontFamily: "Roboto_400Regular",
paddingLeft: "5%",
paddingLeft: "5%",
color:
theme === true
? Colors.dark.postDateText
: Colors.light.postDateText,
width: "80%",
}}
value={comment}
onChangeText={(value) => {
setComment(value);
}}
maxLength={150}
clearButtonMode="always"
multiline={true}
placeholder="Write your comments here..."
placeholderTextColor={Colors.light.postDateText}
onSubmitEditing={() => Keyboard.dismiss()}
/>
//button code to submit comment
<TouchableOpacity
onPress={() => {
addComment(comment);
// Keyboard.dismiss();
}}
style={{ width: "20%", marginLeft: 10 }}
>
<SvgCommentArrow />
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
It may happened due to not specifying the keyboard type in the textinput props https://reactnative.dev/docs/textinput#keyboardtype.
also refer this
https://reactnative.dev/docs/keyboard

Flat List renderItem width issue

I have some flat lists in my app with an item width of 160. For some reason when I reduce the width to 130 it will work as planned but with a width of 160px it starts to rerender again and again. What will be the possible reason for this and how to fix the issue.
My code
<FlatList
horizontal
inverted={getFlatListOrientation()}
data={data}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => renderItem(item, index)}
contentContainerStyle={styles.listContainerStyle}
showsHorizontalScrollIndicator={false}
/>
this is my render item component
<TouchableWithoutFeedback
onPress={() => {
this.onSelect();
}}
>
<View style={{ height: 168,
width: 130,
marginRight: 10,
backgroundColor: kBackgroundWhiteColor,
shadowColor: kSeparatorTintColor,
shadowOffset: { width: 1, height: 1 },
shadowOpacity: 0.5,
shadowRadius: 5,
borderRadius: 5,
elevation: 10,}>
<FastImage
style={styles.imageStyle}
resizeMode={FastImage.resizeMode.cover}
source={
loadingError
? PLACE_HOLDER_IMAGE
: {
uri: photoUrl,
priority: FastImage.priority.normal,
}
}
onLoad={() => {
this.setState({ loadingImage: false });
}}
onError={() => {
this.setState({ loadingError: true });
}}
>
<View
style={{
flexDirection: "row",
flexGrow: 1,
justifyContent: "space-between",
alignItems: "center",
transform: [
{
rotateY: isKSA() ? "180deg" : "0deg",
},
],
}}
>
<TouchableOpacity
style={{
right: 0,
bottom: 0,
position: "absolute",
}}
onPress={() => this.onAddCarTofavorites()}
>
<View style={{ paddingLeft: 8, paddingTop: 8 }}>
<View
style={{
width: 26,
height: 26,
alignItems: "center",
justifyContent: "center",
borderRadius: 13,
backgroundColor: "#00000033",
marginRight: 5,
marginBottom: 5,
}}
>
<Image
source={
isFavorited
? IC_HEART_FILLED
: IC_HEART_OUTLINE
}
style={styles.favoriteImageStyle}
backgroundColor="clear"
/>
</View>
</View>
</TouchableOpacity>
{seenCarsIdlist &&
seenCarsIdlist.indexOf(id + "") != -1 && (
<Seen />
)}
{cappasity_link && <Tag3D />}
</View>
</FastImage>
{loadingImage && (
<FastImage
style={{
...styles.mainImageStyle,
position: "absolute",
}}
resizeMode={FastImage.resizeMode.cover}
source={PLACE_HOLDER_IMAGE}
/>
)}
<View style={styles.innerContainerStyle}>
<Text
style={styles.titleTextStyle}
ellipsizeMode={"tail"}
numberOfLines={1}
>
{makeName && modelName
? `${makeName} ${modelName} ${trim}`
: `${title} ${trim}`}
</Text>
<Text style={styles.priceTextStyle}>
{price + translate("filter_label_sar")}
</Text>
<View style={{ flexDirection: "row", paddingTop: 10 }}>
<Text style={styles.yearMileageTextStyle}>
{`${year} ยท ${mileage} ${
mileageUnitTemp
? mileageUnitTemp
: mileageUnit
}`}
</Text>
</View>
</View>
</View>
</TouchableWithoutFeedback>

Display a Modal on a holding modal on react native

I was trying to display a modal on another model its visibility always set to true. I tried multiple ways but still I am unable to show that modal. I am printing here the code to make it a sense:
function Search({navigation}) {
const [number, setNumber] = useState('');
const [visible, setvisible] = useState(false);
return (
<View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)'}}>
<Modal
visible={true}
transparent={true}
style={{
elevation: 24,
borderRadius: 24,
marginTop: 60,
backgroundColor: '#fafcff',
}}>
<View
style={{
margin: 50,
padding: 10,
borderRadius: 35,
height: 40,
flexDirection: 'column',
justifyContent: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 12,
},
shadowOpacity: 0.58,
shadowRadius: 16.0,
elevation: 24,
}}>
<TextInput
label="Enter a phone number"
value={textInput}
keyboardType="numeric"
maxLength={12}
mode="outlined"
dense={true}
// ref={textInput.current.clear()}
theme={{
colors: {
primary: '#00aaff',
},
}}
onChangeText={(text) => {
setNumber(text);
}}
/>
<Button
mode="contained"
theme={{
colors: {
primary: '#006aff',
},
}}
style={{
margin: 70,
marginTop: 10,
padding: 2,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 5,
},
shadowOpacity: 0.34,
shadowRadius: 6.27,
justifyContent: 'center',
elevation: 18,
borderRadius: 18,
textAlign: 'center',
}}
onPress={() => {
if (number === '') {
<Modal visible={!visible} transparent={true} animationType={'fade'}>
<View style={styles.mainOuterComponent}>
<View style={styles.mainContainer}>
{/* First ROw - Alert Icon and Title */}
<View style={styles.topPart}>
{true && (
<Image
source={require('../images/ic_notification.png')}
resizeMode={'contain'}
style={styles.alertIconStyle}
/>
)}
<Text style={styles.alertTitleTextStyle}>
{/* {`${alertTitleText}`} */} Here worked
</Text>
</View>
{/* Second Row - Alert Message Text */}
<View style={styles.middlePart}>
<Text style={styles.alertMessageTextStyle}>
{/* {`${alertMessageText}`} */} EMpty value
</Text>
</View>
{/* Third Row - Positive and Negative Button */}
<View style={styles.bottomPart}>
{true && (
<TouchableOpacity
// onPress={this.onPositiveButtonPress}
style={styles.alertMessageButtonStyle}>
<Text style={styles.alertMessageButtonTextStyle}>
{/* {positiveButtonText} */} Okay
</Text>
</TouchableOpacity>
)}
</View>
</View>
</View>
</Modal>
} else {
console.log('Do Nothing!');
}
}}>
<Text
style={{
fontSize: 25,
color: 'white',
textAlign: 'center',
}}>
{' '}
<MaterialCommunityIcons
name="database-search"
size={40}
color="yellow"
style={{
paddingRight: 5,
alignItems: 'center',
margin: 5,
}}></MaterialCommunityIcons>
Search
</Text>
</Button>
</Modal>
</View>
)
}
expected that when user clicks "search" while the input is empty, a modal showing empty value entered. I got nothing, no error. How can I solve this?
Make two components, then render it based on conditions inside one modal, I used this way for many components.
const ModalContent = ({toggleModal}) => {
const [defaultContent, setDefaultContent] = useState(true);
const conditionalRendering = ()=> {
if(defaultContent === true) return (
<View>
<TouchableOpacity onPress={()=> setDefaultContent(false)}>
<Text>First Content</Text>
</TouchableOpacity>
</View>
);
return (
<View>
<TouchableOpacity onPress={()=> setDefaultContent(true)}>
<Text>Second Content</Text>
</TouchableOpacity>
</View>
);
}
return (
<View style={{flex:1, justifyContent: 'center', alignItems: 'center'}}>
{conditionalRendering()}
</View>
);
}
<Modal
useNativeDriver
onBackButtonPress={toggleModal}
isVisible={modalVisible}
style={{ padding: 0, margin: 0, justifyContent: 'center' }}
>
<ModalContent toggleModal={toggleModal} />
</Modal>

Resources