React-native Keyboard.dismiss dismisses the keyboard when using it - javascript

i am trying to use Keyboard.dismiss() inside of a TouchableWithoutFeedback element and for some reason, no matter where i place this TouchableWithoutFeedback element, the keyboard doesn't dismiss when tapping on areas outside the TextInput,
but it does dismiss when tapping the keyboard itself!
why does this happen and how do i fix it?
p.s. it worked fine on a different project
Message for Stack Overflow staff: many of my threads are being locked for "not being clear" even though i am being very thorough in each and every one of them
DO NOT LOCK THIS THREAD
the code:
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss()}>
<View style={styles.mainView}>
<View style={styles.topSearchView}>
<Image source={require("../../assets/NewSearchIcon.png")} style={styles.searchIcon} />
<TextInput
placeholder="Search for food you like..."
onChangeText={searchedCoursesHandler}
value={searchedCourses}
onFocus={() => { setInputBorderOnFocus(true) }}
style={{
borderColor: inputBorderOnFocus === true ? "#428463" : "grey",
borderWidth: 2,
width: 260,
height: 50,
marginLeft: 10,
fontSize: 18,
padding: 5,
borderRadius: 8,
fontSize: 16
}}
/>
<TouchableOpacity
onPress={() => { setSearchedCourses("") }}
style={styles.deleteInputTouchable}
>
<Image source={require("../../assets/newXicon.png")} style={styles.xButtonIcon} />
</TouchableOpacity>
</View>
<View style={styles.flatListView}>
<FlatList
data={searchedCourses}
renderItem={({ item }) => (
<TouchableOpacity
onPress={() => {
navigation.navigate('item profile', {
item: item,
});
}}
>
<View style={styles.flatListItemView}>
<Image source={{ uri: item.img }} style={styles.flatListImg} />
<Text>{item.name}</Text>
<Text>{item.price}$</Text>
</View>
</TouchableOpacity>
)}
horizontal={true}
/>
</View>
{
searchedCourses.length < 1 &&
<Image source={require("../../assets/NewPastaImage.png")} style={styles.pastaIcon} />
}
</View>
</TouchableWithoutFeedback>
);
enter code here

Change This <TouchableWithoutFeedback onPress={Keyboard.dismiss()}>
into this
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>

Related

Why my Keyboard not pushing up input view in React Native?

I have a Sign Up screen in React Native, and when I press on the Input fields, my view does not go up therefore I can not see what I am typing. On other screens I have, the view gets pushed up. It feels like on Sign Up screen the "keyboardLayout" is set to "pan", but I did not specify it anywhere...
I am using Expo.
SignUp.js
return(
<View style={styles.container}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logoStyle}/>
</View>
<View>
<Formik
initialValues={{email:'', fullname:'',password:'', password_repeat:'', adatkezeles:false}}
onSubmit={values =>{
onRegister_clicked(values.email,values.password,values.fullname)
}}
validationSchema={SignUpFormSchema}
validateOnMount={true}
>
{({handleChange, handleBlur, handleSubmit, values, isValid, errors, setFieldValue}) => (
<>
<View style={[styles.textBox,{
borderColor: values.email.length < 1 || emalValidate(values.email) ? color_theme_light.textBoxBorder : color_theme_light.loginTextInvalid
}]}>
<TextInput
placeholder='Email cím'
autoCapitalize='none'
keyboardType='email-address'
textContentType='emailAddress'
autoFocus={true}
caretHidden={false}
//Formik
onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}
/>
</View>
<View style={[styles.textbox_information,{borderColor: 1 > values.password.length ||values.password.length >= 6 ? color_theme_light.textBoxBorder : color_theme_light.loginTextInvalid}]}>
<TextInput
placeholder='Jelszó'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={passwordVisible}
textContentType='password'
//Formik
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
style={{width:(window.width)*0.75}}
/>
{passwordVisible ?
<TouchableOpacity onPress={onClick_setPasswordVisible}>
<Entypo name="eye-with-line" size={27} color={color_theme_light.iconColor} />
</TouchableOpacity>
:
<TouchableOpacity onPress={onClick_setPasswordVisible}>
<Entypo name="eye" size={27} color={color_theme_light.iconColor} />
</TouchableOpacity>
}
</View>
<View style={[styles.textbox_information,{borderColor:color_theme_light.textBoxBorder}]}>
<TextInput
placeholder='Jelszó megismétlése'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={passwordVisible}
textContentType='password'
//Formik
onChangeText={handleChange('password_repeat')}
onBlur={handleBlur('password_repeat')}
value={values.password_repeat}
style={{width:(window.width)*0.75}}
/>
</View>
{errors.password_repeat ?
<Text style={{color:'red', textAlign:'center', fontFamily:'QuicksandMedium'}}>{errors.password_repeat}</Text>
: null }
<View style={[styles.textBox,{
borderColor: 1 > values.fullname.length ||values.fullname.length >= 2 ? color_theme_light.textBoxBorder : color_theme_light.loginTextInvalid
}]}>
<TextInput
placeholder='Név'
autoCapitalize='words'
autoCorrect={false}
textContentType='name'
//Formik
onChangeText={handleChange('fullname')}
onBlur={handleBlur('fullname')}
value={values.fullname}
/>
</View>
<View style={{flexDirection:'row', alignItems:'center', justifyContent:'center',paddingTop:10}}>
<TouchableOpacity onPress={() => setFieldValue('adatkezeles', !values.adatkezeles)}>
{!values.adatkezeles ? <Ionicons name="square-outline" size={27} color={color_theme_light.iconColor} />
:
<Ionicons name="ios-checkbox" size={27} color={color_theme_light.iconColor} />
}
</TouchableOpacity>
<Text style={[fontStyles.baseText,{fontSize:13}]}>Elolvastam és elfogadom az </Text>
<TouchableOpacity onPress={() => setAdatkezelesModal(true)}>
<Text style={[fontStyles.baseText, {color:color_theme_light.loginLink, fontSize:13}]}>adatkezelési nyilatkozatot</Text>
</TouchableOpacity>
</View>
{adatkezelesModal ? <OpenAdatkezeles/> : null}
<View style={{alignItems:'center', justifyContent:'center', marginTop:20}}>
<TouchableOpacity onPress={handleSubmit}>
<View style={[styles.button(isValid),styles.shadow]}>
{!buttonLoading.loading ?
<Text style={fontStyles.loginButtonText}>Regisztráció</Text>
: <ButtonLoading/>}
</View>
</TouchableOpacity>
</View>
<View style={styles.signUpContainer}>
<Text style={fontStyles.baseText}>Már rendelkezel egy fiókkal?</Text>
<TouchableOpacity onPress={()=> navigation.navigate('LoginScreen')}>
<Text style={[fontStyles.baseText, {color:color_theme_light.loginLink}]}> Belépés</Text>
</TouchableOpacity>
</View>
</>
)}
</Formik>
</View>
</View>
)
}
you can either use KeyboardAvoidingView or make a custom keyboard avoiding view yourself.
also when using KeyboardAvoidingView dont forget to specify the behavior prop.
here is an example of custom keyboard avoiding view
import React, { useEffect, useRef } from 'react';
import { Keyboard, KeyboardEvent, Animated, Platform } from 'react-
native';
import { heightPercentageToDP as hp } from 'react-native-responsive-screen';
function CustomKeyboardAvoidingView(props: any) {
const heightAnim = useRef(new Animated.Value(hp('100%'))).current
function onKeyboardDidShow(e: KeyboardEvent) {
Animated.spring(heightAnim, {
toValue: hp('100%') - e.endCoordinates.height,
overshootClamping: true,
bounciness: 1,
speed: Platform.OS == 'ios'? 18 : 50,
useNativeDriver: false,
}).start()
}
function onKeyboardDidHide() {
Animated.spring(heightAnim, {
toValue: hp('100%'),
overshootClamping: true,
bounciness: 5,
speed: Platform.OS == 'ios'? 18 : 50,
useNativeDriver: false,
}).start()
}
useEffect(() => {
const SHOW_KEYBOARD_EVENT = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow'
const HIDE_KEYBOARD_EVENT = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide'
const showSubscription = Keyboard.addListener(SHOW_KEYBOARD_EVENT, onKeyboardDidShow);
const hideSubscription = Keyboard.addListener(HIDE_KEYBOARD_EVENT, onKeyboardDidHide);
return () => {
showSubscription.remove();
hideSubscription.remove();
};
}, []);
return (
<Animated.View style={[{
height: heightAnim,
}]} >
{props.children}
</Animated.View>
)
}
I managed to solve it with the following way:
<KeyboardAvoidingView>
<ScrollView>
{*Rest of the code*}
</ScrollView>
</KeyboardAvoidingView>
I honestly dont know why, but this moves up my view when I want to type.

React Native - How to set blurRadius onto a selected image

My app displays images and other info getting data from a JSON, and I want to set a blurRadius on the selected image when the unblur function is called.
My code is the following:
const [blur, setBlur] = useState(160);
const unblur = () => {
if(blur == 160){
setBlur(0);
}
}
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
<Image style={{ alignSelf: "center" }} source={{uri: item.profile_picture, width: 48, height: 48}} />
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image style={{ alignSelf: "center" }} blurRadius={blur} source={{uri: item.picture, width: 400, height: 320}} />
</TouchableOpacity>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{'\n'}{'\n'}
</Text>
</>
)}
/>
)}
I want to change the {blur} value for a given image when I tap the TouchableOpacity component of the image I want to unblur. Right in this moment when I tap an image, all the images in the list are getting unblurred.
You should add the blur values inside your items like this. Create a new components called Items. Then, add the blur state inside it. (not inside Main).
const Main = () => {
if (isLoading) {
return;
<ActivityIndicator />;
}
return (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Item item={item} />}
/>
);
};
const Item = ({ item }) => {
const [blur, setBlur] = useState(160);
const unblur = () => {
if (blur == 160) {
setBlur(0);
}
};
return (
<>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
<Image
style={{ alignSelf: "center" }}
source={{ uri: item.profile_picture, width: 48, height: 48 }}
/>
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image
style={{ alignSelf: "center" }}
blurRadius={blur}
source={{ uri: item.picture, width: 400, height: 320 }}
/>
</TouchableOpacity>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{"\n"}
{"\n"}
</Text>
</>
);
};
Also, may I suggest you can use 'onPressIn'. That way, image will unblur when the finger tap the image, not press the image. But that was your decision.

Using a variable for a createDrawerNavigation

I am working on a simple React Native e-commerce app and i ran into a issue. I am trying to add the option to change the language, and it has worked so far with the Redux but now i need to dynamically change the sidebar menu and I cant because it is hardcoded as a prop.The code for the menu is this.
const ShopNavigator = createDrawerNavigator(
{
Produktetee: ProductsNavigator,
Rezervimet: OrdersNavigator,
Postoni: AdminNavigator},
{
contentOptions: {
activeTintColor: MyColors.primary
},
contentComponent: props => {
const {log_out} = useSelector(state => state.language)
const dispatch = useDispatch();
return (
<View style={{ flex: 1, paddingTop: 50 }}>
<SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
<DrawerItems {...props} />
<Button
title={log_out}
color={MyColors.primary}
onPress={() => {
dispatch(authActions.logOut());
// props.navigation.navigate("Auth");
}}
/>
<View style={{flexDirection: 'row'}}>
<View style={{flex:1 , marginRight:10, marginTop: 5,}} >
<Button
title="English"
type="outline"
color={MyColors.primary}
onPress={()=>{
dispatch(index.selectLanguage(languages.english))
}}
/>
</View>
<View style={{flex:1, marginTop: 5,}} >
<Button
title="Shqip"
type="outline"
color={MyColors.primary}
onPress={()=>{
dispatch(index.selectLanguage(languages.albanian))
}}
/>
</View>
</View>
</SafeAreaView>
</View>
);
}
}
);
I am trying to use the hook, but I can't. If somebody could help me I would be very grateful.

TextInput in FlatList Item

I have a problem like picture below:
Text
As you guy can see I have info on every item: name and stock. Now I want to update stock on single item by type a number to text Input But when I type 3 into 1 Text Input, it fills 3 in all the remaining Text Input. This is my render Item:
renderItem = ({item}) => {
return (
<View style={styles.card}>
<TouchableOpacity
onPress={() => {
setCreateAt(item.WarehouseProduct.createdAt);
setNote(item.note);
setShowModal(true);
}}>
<Image
style={styles.tinyLogo}
source={require('../assets/images/fish.jpg')}
/>
</TouchableOpacity>
<View
style={{
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
marginLeft: 5,
height: 75,
width: 160,
}}>
<Text numberOfLines={2} style={styles.text}>
{item.name}
</Text>
<Text style={styles.text}>
{item.WarehouseProduct.stock.toString()}
</Text>
</View>
<View style={styles.iconcontainer}>
<Button title="clear" onPress={() => console.log(text)} />
</View>
<View
style={{
alignSelf: 'center',
marginLeft: 20,
borderWidth: 1,
borderRadius: 10,
}}>
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(income) => setText(income)}
value={text}
/>
</View>
</View>
);
};
Can anyone help me solve this problem? Just give me an idea. Thanks all!
anything you put in renderitem will be rendered as much as your data in flatlist
<Flatlist
data={containtmultipledata}
renderItem={
....
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(income) => setText(income)}
value={text}
/>
....
}
>
but you asign it to single value
you can change data you put in flatlist directly by index in item
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(txt) => containMultipledata[index].yourObjectName = txt}
value={item.yourObjectName}
/>
Try this way
const [data, setData] = useState([... flat list data here default]);
const onTextChanged = (index, value) => {
const data = [...data];
data[index].availableStock = value; <-- "availableStock" is example key for showing way out of this -->
setData(data);
}
renderItem = ({item, index}) => {
return (
<View style={styles.card}>
......
<TextInput
...
onChangeText={(income) => onTextChanged(index, income)}
value={item.availableStock || 0}
/>
</View>
);
};

How can I collapse Item pressed on arrays - react native?

I have a list of cards,
when pressed to any of them, I want to Increase hight for that card,
So I use layoutAnimation to handle this case because when I use Animated API from RN, I got an error when setNativeDrive "height"
Anyway,
In my case, it increases height for every card in the list,
So how can I solve it?
Code snippet
Live Demo
const OpenedAppointments = ({slideWidth}) => {
const [currentIndex, setCurrentIndex] = React.useState(null);
const [cardHeight, setCardHeight] = useState(140);
const collapseCard = (cardIndex) => {
setCurrentIndex(cardIndex);
currentIndex === cardIndex
? (LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut),
Animated.spring(),
setCardHeight(200))
: (LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut),
Animated.spring(),
setCardHeight(140));
};
const renderItems = (item, index) => {
return (
<TouchableOpacity
delayPressIn={0}
onPress={() => collapseCard(index)}
key={item.id}>
<Animated.View
style={[
styles.itemContainer,
{
height: cardHeight,
},
]}>
<View style={styles.headerContainer}>
<View style={styles.imgContainer}>
<Image
resizeMode="cover"
style={styles.img}
source={{uri: item.vendorInfo.vendorImg}}
/>
</View>
<View style={{width: '80%'}}>
<View style={styles.titleContainer}>
<Text numberOfLines={1} style={styles.vendorName}>
{item.vendorInfo.name}
</Text>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Text style={styles.rateText}>{item.vendorInfo.rate}</Text>
<AntDesign name="star" size={18} color="#262626" />
</View>
</View>
<View style={styles.socialContainer}>
<View
style={{
width: 32,
height: 32,
backgroundColor: '#000',
borderRadius: 5,
}}
/>
</View>
</View>
</View>
<View style={styles.footer}>
<Text style={styles.serviceName}>
{item.serviceName}
</Text>
<Text style={styles.price}>
{item.price}
</Text>
</View>
// this will appeared when pressed to card "Footer Card"
<View>
<View style={styles.line} />
<View style={styles.editFooter}>
<View style={styles.dateContainer}>
<MemoCalender
style={styles.calenderIcon}
size={26}
color="#000"
/>
<View style={styles.dateBox}>
<Text style={styles.dateText}>{item.date}</Text>
<Text style={styles.dateText}>{item.time}</Text>
</View>
</View>
</View>
</View>
</Animated.View>
</TouchableOpacity>
);
};
return(
<>
{Data.opened.map((item, index) => renderItems(item, index))}
</>
);
}
Change this:
<Animated.View
style={[
styles.itemContainer,
{
height: cardHeight,
},
]
>
{...}
</Animated.View>
by
<Animated.View
style={[
styles.itemContainer,
{
height: currentIndex === index ? cardHeight : 140,
},
]
>
{...}
</Animated.View>
If you want to be more efficient, the default height of your card, define it in a constant (ex: const = DEFAULT_CARD_HEIGHT = 140) and use this constant wherever you use 140 as card height

Categories