How to set keyboard off at beginning on React Native - javascript

My app at first opening direct a login page and keyboard open automaticly! But what i want is keyboard off position at beginning but when clicking any input must be keyboard on.Here is my login.js page
import React, { Component } from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';
import Axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
Image,
ActivityIndicator,
} from 'react-native';
import { Container, Header, Content, Form, Item, Input, Button } from 'native-base';
import { set } from 'react-native-reanimated';
export default class Login extends Component {
render() {
return (
<ScrollView contentInsetAdjustmentBehavior="automatic" >
<View style={styles.containerx}>
<Container style={styles.bigContainer} >
<Content contentContainerStyle={{ flex: 1, justifyContent: 'center', padding: 30 }}>
<Image
source={ require('../assets/icon1024.png') }
style={{ width: 150, height: 150, alignSelf: 'center', marginBottom: 10 }}
/>
<Text style={styles.loginText}>KUŞ SOR</Text>
<Text style={[styles.loginText, { fontSize: 14 }]} >Birdpx Kuş Tanımlama Platformu</Text>
{
this.state.loading == true ? <View style={styles.emptyCont}><ActivityIndicator size='large' color='white' /></View> :
<Formik
initialValues={{username: '', password: ''}}
onSubmit={this._handleSubmit}
validationSchema={
Yup.object().shape({
password: Yup.string().min(6, 'Minimim 6 Karakter').required('Bu Alan Zorunludur'),
username: Yup.string().required('Bu Alan Zorunludur'),
})
}
>
{({ handleChange, handleBlur, handleSubmit, values, errors }) => (
<Form>
<Item>
<Input
onChangeText={handleChange('username')}
onBlur={handleBlur('username')}
placeholder="Kullanıcı Adı"
style={{ color: 'white' }}
autoCapitalize={'none'}
value={values.username}
autoFocus={true}
/>
<Text style={styles.errorStyle}>{errors.username}</Text>
</Item>
<Item>
<Input
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
style={{ color: 'white' }}
secureTextEntry={true}
placeholder="Şifre"
value={values.password} />
<Text style={styles.errorStyle}>{errors.password}</Text>
</Item>
<Button style={{ alignSelf: 'center', marginTop: 20, padding: 10 }} warning
block
onPress={handleSubmit}
>
<Text style={{ textAlign: 'center', justifyContent: 'center' }} > GİRİŞ YAP </Text>
</Button>
<View>
<Text
style={{ textAlign: 'center', justifyContent: 'center', color: '#999', marginTop: 150 }}
onPress={() => this.props.navigation.navigate('FSignup')}
>Henüz üye değilseniz. Buradan Kayıt Olun</Text>
</View>
</Form>
)}
</Formik>
}
</Content>
</Container>
</View>
</ScrollView>
);
};
};
const styles = StyleSheet.create({
bigContainer: {
backgroundColor: 'black',
flex: 1,
},
containerx: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
width:'100%'
},
loginText: {
color: '#c79816',
fontSize: 20,
alignSelf: 'center',
margin: 7,
fontWeight: "700"
},
emptyCont: {
flex: 1,
height: 100,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
},
errorStyle: {
fontSize: 15,
color: 'red'
},
});
Tried keyboardAvoidingView element in react native but i can not get a good result
Could you help me please?

you have to manually close it in this case either put the input autoFocus to false or use the manual react-native Keyboard handler like below:
import {Keyboard} from 'react-native'
Now when the component mounts we will close the keyboard.
componentDidMount(){
Keyboard.dismiss();
}

Related

The KeyboardAvoidingView is not behaving the way I want it to

So the code for my login screen is
import {
StyleSheet,
Text,
View,
StatusBar,
SafeAreaView,
TextInput,
ImageBackground,
KeyboardAvoidingView,
} from "react-native";
import React from "react";
import LottieView from "lottie-react-native";
const LoginScreen = () => {
return (
<View style={styles.container} behavior="padding">
<ImageBackground
source={require("../../assets/images/cool-background.png")}
resizeMode="cover"
style={styles.image}
>
<KeyboardAvoidingView style={{ flex: 1 }} behavior="padding">
<View style={styles.lottieContainer}>
<LottieView
source={require("../../assets/lottiejson/login.json")}
autoPlay
/>
</View>
<View style={styles.inputContainer}>
<TextInput placeholder="Email" style={styles.input} />
<TextInput
placeholder="password"
style={styles.input}
secureTextEntry
/>
</View>
</KeyboardAvoidingView>
</ImageBackground>
</View>
);
};
export default LoginScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
flexDirection: "column",
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
},
text: {
color: "white",
fontSize: 42,
lineHeight: 84,
fontWeight: "bold",
textAlign: "center",
backgroundColor: "#000000c0",
},
inputContainer: {
alignItems: "center",
flex: 1,
},
input: {
backgroundColor: "#51C9F9",
width: "75%",
height: 50,
borderRadius: 20,
marginTop: 5,
elevation: 10,
color: "#8FF69C",
padding: 5,
},
lottieContainer: {
width: "100%",
height: 400,
},
});
I want the keyboard to push the entire TextInput View and the lottieContainer up, so that the TextInputs are visible and not hidden by the keyboard, but instead it just doesn't do anything. I tried putting the KeyboardAvoidingView tag encapsulating the ImageBackground and in that case whenever I clicked on the input, half the screen would become white and that's it.

React Native Styling & Flex -- Centering A Component

I'm having incredible difficulty figuring out why my stylesheet isn't working the way that I want it to -- I want both the icon [note the comments] as well as the button on the bottom to appear centered, but both currently appear left-aligned. Would be grateful for any + all direction.
Here are my imports:
import { useNavigation } from '#react-navigation/native';
import React from 'react';
import {
Text,
SafeAreaView,
ScrollView,
View,
TouchableOpacity,
ActivityIndicator,
Alert
} from 'react-native';
import { withNavigation } from 'react-navigation';
import { firebase } from '../../../../firebase/config';
import styles from './styles';
import DateTimePicker from '#react-native-community/datetimepicker';
import { Sae } from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import { FontAwesome } from '#expo/vector-icons'
Here is the code returned from my class component:
<SafeAreaView style={styles.container}>
<ScrollView>
<View style={styles.inputContainer}>
<View>
<Text style={styles.title}>Create An Event</Text>
</View>
<Sae
style={{marginLeft: 10, marginRight: 10, marginBottom: 10}}
labelStyle={{color: '#656565'}}
label={'Event Name'}
iconClass={FontAwesomeIcon}
iconName={'calendar-check-o'}
iconColor={'#e95530'}
inputPadding={16}
labelHeight={20}
borderHeight={2}
autoCapitalize={'none'}
autoCorrect={false}
/>
<Sae
style={{marginLeft: 10, marginRight: 10}}
labelStyle={{color: '#656565'}}
inputStyle={{fontSize: 16}}
label={'Event Description'}
iconClass={FontAwesomeIcon}
iconName={'pencil'}
iconColor={'#e95530'}
inputPadding={16}
labelHeight={20}
borderHeight={2}
autoCapitalize={'none'}
autoCorrect={false}
/>
<View style={styles.break1}></View>
<View style={styles.break2}><FontAwesome name='circle' color='#e6a80c'/></View> //would like this icon to be centered
<View style={styles.break3}></View>
<View style={styles.indInputContainer}>
<Text style={styles.text}>Date </Text>
<DateTimePicker
testID='datePicker'
value={this.state.date}
mode='date'
is24Hour={true}
display='default'
onChange={this.onChange}
placeholder='Select a date'
style={{ marginHorizontal: 10 }}
/>
</View>
<View style={styles.indInputContainer}>
<Text style={styles.text}>Start Time </Text>
<DateTimePicker
testID='timePicker'
value={this.state.eventStartTime}
mode='time'
is24Hour={true}
display='default'
onChange={this.onChange}
placeholder='Start time'
style={{ marginHorizontal: 10 }}
/>
</View>
<View style={styles.indInputContainer}>
<Text style={styles.text}>End Time </Text>
<DateTimePicker
testID='timePicker'
value={this.state.eventEndTime}
mode='time'
is24Hour={true}
display='default'
onChange={this.onChangeEventEndTime}
placeholder='End time'
style={{ marginHorizontal: 10 }}
/>
</View>
<View style={styles.indInputContainer}>
<Text style={styles.text}>Guests' Votes Due By </Text>
<DateTimePicker
testID='datePicker'
value={this.state.votingDeadline}
mode='date'
is24Hour={true}
display='default'
onChange={this.onChangeVotingDeadline}
placeholder='Votes Due By'
style={{ marginHorizontal: 10 }}
/>
</View>
</View>
<View style={styles.buttonContainer}> //would like this button to appear centered also
<TouchableOpacity
style={styles.button}
onPress={() => this.storeEvent()}
>
<Text style={styles.Btn}>Create Event</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
And here is the stylesheet:
export default StyleSheet.create({
container: {
backgroundColor: '#ffffff',
flex: 1,
justifyContent: 'center'
},
inputContainer: {
padding: 10
},
indInputContainer: {
margin: 8
},
break1: {
marginBottom: 20,
marginTop: 20
},
break2: {
alignContent: 'center',
justifyContent: 'center'
},
break3: {
marginTop: 10,
marginBottom: 10
},
text: {
fontSize: 16,
color: '#656565',
},
preferences: {
fontWeight: 'bold',
fontSize: 20,
margin: 5,
},
title: {
padding: 5,
fontSize: 16,
fontWeight: 'bold',
color: '#e95530'
},
buttonContainer: {
justifyContent: 'center',
alignContent: 'center'
},
button: {
backgroundColor: '#e95531',
margin: 10,
marginTop: 20,
height: 48,
borderRadius: 5,
alignItems: 'center',
justifyContent: 'center',
width: 275,
},
Btn: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
},
});
Would be super grateful for some help. Thank you!

React Native Own font doesnt get applied to all elements

I wanted to implement my own font (from google) to use it inside my app. I loaded it and it works because some text gets changed by it. However some text doenst change which doesnt make sense to me.
I guess its a bug somehow maybe somebody has experienced this. Its a simple screen with simple code.
import React, {Component} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';
import COLORS from '../assets/COLORS';
import {TextInput} from 'react-native-gesture-handler';
class BMI extends Component {
render() {
const BMI = 20;
return (
<View style={styles.container}>
<Text style={styles.textStyle}> BMI - Calculator </Text>
<Text style={{color: COLORS.white, fontSize: 20}} >Dein momentaner BMI: <Text style={{color: COLORS.primary, fontSize: 24}} >{BMI}</Text> </Text>
<View>
<View style={styles.InputContainer}>
<Text style={styles.inputText}>AGE</Text>
<TextInput style={styles.TextInput} />
</View>
<View style={styles.InputContainer}>
<Text style={styles.inputText}>HEIGHT</Text>
<TextInput style={styles.TextInput} />
</View>
<View style={styles.InputContainer}>
<Text style={styles.inputText}>WEIGHT</Text>
<TextInput style={styles.TextInput} />
</View>
<View style={{marginTop: 25, marginHorizontal: 15}}>
<Button onPress={() => alert("Hello")} title="Calculate" color={COLORS.lightB} />
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
// justifyContent: "center",
backgroundColor: COLORS.darkBG,
},
textStyle: {
color: COLORS.lightB,
fontSize: 30,
fontWeight: 'bold',
marginVertical: 30,
fontFamily: "Pacifico"
},
InputContainer: {
justifyContent: 'space-around',
flexDirection: 'row',
width: '100%',
marginVertical: 20,
},
inputText: {
color: COLORS.white,
width: '30%',
marginLeft: 15,
fontSize: 18,
fontFamily: "Pacifico"
},
TextInput: {
backgroundColor: COLORS.primary,
width: '60%',
color: COLORS.white,
fontFamily: "Pacifico"
},
});
export default BMI;
As u can see I load pacifico and it works but only for this text ( see pic below ):

Change initial route after Validation - react-native

I'm struggling to find a solution to my problem, but no success yet.
My idea is: when the user receives the 6 digits code from the API and hits confirm the page will reload and send him to the main app. I have looked around if there is any function that can help me resolve my problem, but the only idea that seems to be working for now is to link the button from the ValidationPage to the rooting stack and give the function onPress to send the user to the MainPage.js.
But my opinion is that this is not the right way to do this. So does anyone have an idea how to tackle this problem? I'll be glad if someone can help me. Thank you! The outlook of the page looks like this :
LoginPage.js
import React, { Component } from 'react';
import { Linking, Image, View, AsyncStorage, Dimensions } from "react-native";
import { Container, Icon, Text, Content, Button, Input, Item } from "native-base";
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {}
}
state = {
fontLoaded: false,
}
async componentWillMount() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
Ionicons: require("#expo/vector-icons/fonts/Ionicons.ttf"),
});
this.setState({ fontLoaded: true });
}
render() {
return (
this.state.fontLoaded ? (
<Container>
<Content>
<View style={{ alignContent: 'center', alignItems: 'center' }}>
<Image
style={{
width: '60%',
height: 200,
}}
source={require('../../assets/images/Shootlog.png')} />
</View>
<Text style={{ textAlign: 'center', lineHeight: 30, fontWeight: 'bold', fontSize: 20, color: 'grey' }}> Welcome to myShootLog</Text>
<Text style={{ textAlign: 'center', color: '#be0202' }}>Smart Shooting Solution for shooting ranges.</Text>
<Text style={{ padding: 20, textAlign: 'center', color: 'grey' }}> To continue , please fill in your email adress :</Text>
<View style={{ alignContent: 'center', alignItems: 'center', margin: 20 }}>
<Item style={{ marginBottom: 10 }}>
<Input
placeholder='example#mail.com'
onChangeText={(text) => this.validate(text)}
value={this.state.email}
keyboardType='email-address'
/>
<Icon name={this.state.emailCheck} />
</Item>
<Button full onPress={() => this.props.navigation.navigate('Validation')} style={{ backgroundColor: '#e72a2e'}}>
<Text style={{ textTransform: 'uppercase', }}>{'send'.toUpperCase()}</Text>
<Icon name='arrow-forward' />
</Button>
</View>
</Content>
<View style={{ width: '100%', alignContent: 'center', position: 'absolute', top: footerTopPosition }}>
<Text style={{ color: 'grey', fontSize: 11, textAlign: 'center' }} >All Rights Reserved.® 2018 by CanDoIt </Text>
<Text style={{ color: 'grey', fontSize: 10, textAlign: 'center' }} onPress={() => Linking.openURL('http://candoit.be')}>www.candoit.be</Text>
</View>
</Container>
) : null
);
}
validate = (text) => {
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false) {
console.log('email is incorrect')
this.setState({ emailCheck: 'close-circle' });
return false;
}
else {
this.setState({ emailCheck: 'checkmark-circle' })
console.log('email is correct')
}
}
}
ValidationPage.js
import React, { Component } from 'react';
import { Linking, Image, View, AsyncStorage, Dimensions } from "react-native";
import { Container, Icon, Text, Content, Button, Input, Item } from "native-base";
export default class ValidationScreen extends Component {
constructor(props) {
super(props);
this.state = {}
}
state = {
fontLoaded: false,
}
async componentWillMount() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
Ionicons: require("#expo/vector-icons/fonts/Ionicons.ttf"),
});
this.setState({ fontLoaded: true });
}
render() {
const { navigate } = this.props.navigation;
return (
this.state.fontLoaded ? (
<Container>
<Content>
<View style={{ alignContent: 'center', alignItems: 'center' }}>
<Image
style={{
width: '60%',
height: 200,
}}
source={require('../../assets/images/Shootlog.png')} />
</View>
<Text style={{ textAlign: 'center', lineHeight: 30, fontWeight: 'bold', fontSize: 20, color: 'grey' }}> Welcome to NicoLog</Text>
<Text style={{ textAlign: 'center', color: '#be0202' }}>Smart Shooting Solution for shooting ranges.</Text>
<Text style={{ padding: 20, textAlign: 'center', color: 'grey' }}> Please fill in the 6 digits code from the email that you have recieved :</Text>
<View style={{ alignContent: 'center', alignItems: 'center', margin: 20 }}>
<Item style={{ marginBottom: 10 }}>
<Input
placeholder='Ex. 910-519'
onChangeText={(text) => this.validate(text)}
value={this.state.email}
keyboardType='number-pad'
/>
<Icon name={this.state.emailCheck} />
</Item>
<Button full onPress={() => this.props.navigation.navigate('Main')} style={{ backgroundColor: '#e72a2e' }}>
<Icon name='checkmark-circle' />
<Text style={{ textTransform: 'uppercase' }}>{'confirm'.toUpperCase()}</Text>
</Button>
<Text style={{ padding: 20, textAlign: 'center', color: 'grey' }}>If you didn't recieved anything please click the button bellow.</Text>
<Button full style={{ backgroundColor: '#e72a2e' }}>
<Icon name='refresh' />
<Text style={{ textTransform: 'uppercase' }}>{'re-send'.toUpperCase()}</Text>
</Button>
</View>
</Content>
<View style={{ width: '100%', alignContent: 'center', position: 'absolute', top: footerTopPosition }}>
<Text style={{ color: 'grey', fontSize: 11, textAlign: 'center' }} >All Rights Reserved.® 2018 by CanDoIt </Text>
<Text style={{ color: 'grey', fontSize: 10, textAlign: 'center' }} onPress={() => Linking.openURL('http://candoit.be')}>www.candoit.be</Text>
</View>
</Container>
) : null
);
}
validate = (text) => {
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false) {
console.log('email is incorrect')
this.setState({ emailCheck: 'close-circle' });
return false;
}
else {
this.setState({ emailCheck: 'checkmark-circle' })
console.log('email is correct')
}
}
callMain = () => {
this.props.callParent(); // accsessing the function from the parent App.js
}
}
Navigation.js
import React from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import LoginScreen from './screens/LoginScreen';
import ValidationScreen from './screens/ValidationScreen';
export default createAppContainer( createStackNavigator (
{
Login: { screen: LoginScreen},
Validation: { screen: ValidationScreen},
},
{
headerMode: 'none'
}
));

React Native, having problems with Flex Box

I'm practicing my React Native programming and I have an issue with the Flex Layout that I don't seem to understand pretty well
I wanted to make my test app look like this image below
Sample App
But in the end, this is what I get. There is some misalignment in the 'Home' text which suppose to be centered properly and a missing gap on the two right icons.
Sample Test App
I have tried putting padding on the two icon but have no luck with in.
Here's my code:
import React from 'react';
import Icon from 'react-native-vector-icons/Feather';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<View style={styles.headerBrandingContainer}>
<Text style={styles.headerBranding}>Brand</Text>
</View>
<View style={styles.headerRowContainer}>
<Icon name="menu" size={30} color="white" />
<Text style={styles.headerRowPage}>Home</Text>
<View style={styles.headerRowIcons}>
<Icon name="filter" size={30} color="white" />
<Icon name="search" size={30} color="white" />
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
headerContainer: {
backgroundColor: '#3498db',
height: 180,
justifyContent: 'center',
},
headerBrandingContainer: {
marginTop: 50,
alignItems: 'center',
},
headerBranding: {
fontSize: 40,
fontWeight: '400',
letterSpacing: 1,
color: '#fff',
},
headerRowContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10
},
headerRowIcons: {
//backgroundColor: 'red',
flexDirection: 'row',
justifyContent: 'space-between',
},
headerRowPage: {
// marginLeft:20,
fontSize: 25,
fontWeight: '500',
color: '#fff',
}
});
To align childs of headerContainer vertically you should use alignItems with the code below :
headerContainer: {
display: 'flex',
backgroundColor: '#3498db',
height: 180,
justifyContent: 'center',
alignItems: 'center'
}
A usefull resource to understand flexbox : https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Remove too your marginTop on headerBrandingContainer styles.
EDIT:
Finally I think the best way is to make some modifications in the component tree so that the headerRowContainer items are all flex elements to 1. In this way, the title is always centered (the views having the same size) and we can now manage the placement of buttons without impacting the rest. It works perfectly for me.
import React from 'react';
import Icon from 'react-native-vector-icons/Feather';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<View style={styles.headerBrandingContainer}>
<Text style={styles.headerBranding}>Brand</Text>
</View>
<View style={styles.headerRowContainer}>
<View style={styles.buttonsContainerLeft}>
<Icon name="menu" size={30} color="white" />
</View>
<View style={styles.titleContainer}>
<Text style={styles.headerRowPage}>Home</Text>
</View>
<View style={styles.headerRowIcons}>
<Icon
name="filter"
size={30}
color="white"
style={styles.filterIcon}
/>
<Icon name="search" size={30} color="white" />
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
},
headerContainer: {
backgroundColor: '#3498db',
height: 180,
justifyContent: 'center'
},
headerBrandingContainer: {
marginTop: 50,
alignItems: 'center'
},
headerBranding: {
fontSize: 40,
fontWeight: '400',
letterSpacing: 1,
color: '#fff'
},
headerRowContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
margin: 10
},
buttonsContainerLeft: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start'
},
titleContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
headerRowIcons: {
flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'flex-end'
},
headerRowPage: {
fontSize: 25,
fontWeight: '500',
color: '#fff'
},
filterIcon: {
marginRight: 20
}
});

Categories