React native: change button size in center screen - reactjs

I am new to React Native currently learning about the technology.
I start create a card layout with buttons inside it.
This is my layout :
<KeyboardAvoidingView
behavior='padding'
keyboardVerticalOffset={50}
style={styles.screen}>
<LinearGradient
colors={['#ffedff', '#ffe3ff']}
style={styles.gradient}>
<Card style={styles.card}>
<ScrollView>
<View style={styles.buttonContainer}>
<Button
color={Colors.primary}
title='ورود'
onPress={() => { }} />
</View>
</ScrollView>
</Card>
</LinearGradient>
</KeyboardAvoidingView>
and this is my stylesheet :
const styles = StyleSheet.create({
screen: {
flex: 1
},
gradient: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
card: {
width: '90%',
height: '80%',
padding: 20
},
buttonContainer: {
alignItems: 'center',
marginVertical: 30,
},
});
and result is:
I want to make button bigger so i added width to buttonContainer but button changed position to left of screen and its size does not change.
buttonContainer: {
width: '40%',
alignItems: 'center',
marginVertical: 30,
},
How could i change button width when it is in the center of screen?

So basically alignSelf:'center' was the problem. Removing that worked. Check the expo link below and the code :
import React from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
KeyboardAvoidingView,
ScrollView,
Button
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient'
import Card from './Card';
export default AuthScreen = () => {
return (
<KeyboardAvoidingView
behavior='padding'
keyboardVerticalOffset={50}
style={styles.screen}>
<LinearGradient
colors={['#ffedff', '#ffe3ff']}
style={styles.gradient}>
<Card style={styles.card}>
<ScrollView>
{/* <View style={styles.wcContainer}>
<Text style={styles.headerText}>خوش آمدید</Text>
</View> */}
{/* <View style={styles.container}>
<Text style={styles.text}>نام کاربری</Text>
<TextInput style={styles.input} />
<Text style={styles.text}>رمز عبور</Text>
<TextInput style={styles.input} />
</View> */}
<View style={styles.buttonContainer}>
<Button
color= 'red'
title='ورود'
style={{marginHorizontal:200}}
onPress={() => { }} />
</View>
</ScrollView>
</Card>
</LinearGradient>
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1
},
gradient: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
card: {
width: '90%',
height: '80%',
padding: 20
},
buttonContainer: {
// marginHorizontal:200,
width:'100%',
// alignItems: 'center',
// marginVertical: 30,
justifyContent:'center'
},
});
expo link : expo link
hope it helps. feel free for doubts

I fixed this problem with :
buttonContainer: {
width: '40%',
alignSelf: 'center',
marginVertical: 30,
}
Now this is my layout:

Related

How to update screen dimensions in react native

I have been trying to update my screen dimensions in react native so that the component resizes on-screen rotation with no vain. I have created my style in a separate file (Styles.js) and imported the styles in my login page like below:
Styles.js
import {
StyleSheet,
Dimensions
} from "react-native";
import {
scale,
ScaledSheet
} from "react-native-size-matters";
const styles = ScaledSheet.create({
scrollViewContainer: {
backgroundColor: '#E20030',
alignItems: 'center',
height: Dimensions.get('window').height,
padding: '50#s'
},
container2: {
alignItems: 'center',
justifyContent: 'center',
width: Dimensions.get('window').width,
flex: 1,
},
loginRect: {
borderRadius: '30#s',
marginTop: '20#s',
width: Dimensions.get('window').width * 0.8,
backgroundColor: 'white',
alignItems: 'center'
},
SectionStyle: {
flexDirection: 'row',
marginTop: 0,
marginLeft: '35#s',
marginRight: '35#s',
borderWidth: '1#s',
borderRadius: '5#s',
borderColor: '#dadae8',
},
});
Login.js
import React, { } from 'react';
import {
Text, View, TextInput, TouchableOpacity,
KeyboardAvoidingView,
} from 'react-native';
import { mystyles, styles } from './Components/styles';
const LoginScreen = () => {
return (
<View style={mystyles.scrollViewContainer}>
<KeyboardAvoidingView behavior="padding" style={{ flex: 100 }}>
<View style={mystyles.scrollViewContainer}>
<View style={mystyles.loginRect}>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1, marginLeft: 45, marginTop: 20 }}>
<Text style={{ color: 'black' }}>Username</Text>
</View>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.input}
/>
</View>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1, marginLeft: 45, marginTop: 20 }}>
<Text style={{ color: 'black' }}>Password</Text>
</View>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.input}
/>
</View>
<TouchableOpacity>
<Text style={styles.buttonTextStyle}>LOGIN</Text>
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
</View>
)
}
export default LoginScreen;
So I have tried using Dimensions onchange listener in my Styles.js but I get an error
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
I created this function in the Styles.js file
m
function getDimensions() {
const [dimensions, setDimensions] = useState({
window,
screen
});
useEffect(() => {
const subscription = Dimensions.addEventListener(
"change",
({
window,
screen
}) => {
setDimensions({
window,
screen
});
console.log(dimensions.window.height + " +++ " + dimensions.screen)
}
);
// return () => subscription?.remove();
});
return dimensions.window;
}
Is there any way I can update the component sizes once the screen has been rotated?
This is working for me to detect rotation or changes in the size of the screen (split mode in tablets for example) without eventListeners.
import { Dimensions } from "react-native";
...
useEffect(() => {
...
}, [Dimensions.get("screen").height, Dimensions.get("screen").width]);
Hope this help to anybody

Animated Header with ScrollView is not working

this is my profile page I want scroll animation but I didn't get output
** there is two-part one is header and body part is fully based on card view **
import React, { useRef } from 'react';
import {
StyleSheet,
Text,
View,
Image,
Animated,ScrollView
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import {Card, Title, Paragraph } from 'react-native-paper';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import SafeAreaView from 'react-native-safe-area-view';
import AnimatedHeader from 'C:\Users\keerthana\Desktop\mobile-client-1\src\components\AnimatedHeader.js';
const SettingsScreen=()=>{
const offset = useRef(new Animated.Value(0)).current;
return ( <SafeAreaProvider>
<SafeAreaView style={{ flex: 1 }} forceInset={{ top: 'always' }}>
<AnimatedHeader animatedValue={offset} />
<ScrollView
style={{ flex: 1, backgroundColor: 'white' }}
contentContainerStyle={{
alignItems: 'center',
paddingTop: 220,
paddingHorizontal: 20
}}
showsVerticalScrollIndicator={false}
scrollEventThrottle={16}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: offset } } }],
{ useNativeDriver: false }
)}
>
<View style={styles.header}>
<View style={styles.headerContent}>
<Image style={styles.avatar} source={{uri: 'https://bootdey.com/img/Content/avatar/avatar2.png'}}/>
<Text style={styles.name}>
Name
</Text>
</View>
<View style={{ backgroundColor: "#FFF"}}>
<Card style={{padding:5,borderWidth: 1,borderRadius: 1,borderColor: '#adacac',marginTop:20}}>
<Card.Title title="INFO" subtitle="username" />
<Card.Content>
<Title style={{fontSize:16}}>Phone Number</Title>
<Paragraph>0000000000000</Paragraph>
</Card.Content>
<Card.Content style={{borderWidth: 0, borderColor: 'transparent', elevation: 0}}>
<Title style={{fontSize:16}}>Slogan</Title>
<Paragraph >Testing leads to failure, and failure leads to understanding</Paragraph>
</Card.Content>
</Card>
<Card style={{padding:5,borderWidth: 1,borderRadius: 1,borderColor: '#adacac',marginTop:10}}>
<Card.Title title="Groups" />
</Card>
<View style={{padding:5,borderWidth: 1,borderRadius: 1,borderColor: '#adacac',marginTop:10}}>
//group
<TouchableOpacity>
<View style={{flex: 1,justifyContent: 'center',marginLeft:20}}>
<Image
width={450}
containerStyle={{flex: 0.37}}
imageProps={{resizeMode:'cover'}}
source={{uri: 'https://bootdey.com/img/Content/avatar/avatar2.png'}}
activeOpacity={0.7}
/>
</View>
<View style={{flex: 11,flexDirection: 'column',justifyContent: 'center'}}>
<View style={{ flexDirection: 'row',justifyContent: 'flex-start', marginLeft: 9 }}>
<Text >music game</Text>
</View></View>
</TouchableOpacity>
<TouchableOpacity>
<Text>ludo game</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text> game</Text>
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
</SafeAreaView>
</SafeAreaProvider>
);
};
export default SettingsScreen;
const styles=StyleSheet.create({
header:{
backgroundColor: "#e6e3e3",
},
headerContent:{
padding:30,
alignItems: 'center',
},
avatar: {
width: 130,
height: 130,
borderRadius: 63,
borderWidth: 4,
borderColor: "white",
marginBottom:10,
},
name:{
fontSize:22,
color:"#FFFFFF",
fontWeight:'600',
},
profileDetail:{
alignSelf: 'center',
marginTop:200,
alignItems: 'center',
flexDirection: 'row',
position:'absolute',
backgroundColor: "#ffffff"
},
detailContent:{
margin:10,
alignItems: 'center'
},
title:{
fontSize:20,
color: "#00CED1"
},
count:{
fontSize:18,
},
bodyContent: {
flex: 1,
alignItems: 'center',
padding:30,
marginTop:40
},
textInfo:{
fontSize:18,
marginTop:20,
color: "#696969",
},
buttonContainer: {
marginTop:10,
height:45,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:20,
width:250,
borderRadius:30,
backgroundColor: "#00CED1",
},
description:{
fontSize:20,
color: "#00CED1",
marginTop:10,
textAlign: 'center'
},
});
animation page
** this animation is used for profile page scroll **
import React from 'react';
import {
Animated,
TouchableOpacity,
View,
Text,
StyleSheet
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
const HEADER_HEIGHT = 200;
const AnimatedHeader = ({ animatedValue }) => {
const insets = useSafeAreaInsets();
const headerHeight = animatedValue.interpolate({
inputRange: [0, HEADER_HEIGHT + insets.top],
outputRange: [HEADER_HEIGHT + insets.top, insets.top + 44],
extrapolate: 'clamp'
});
return (
<Animated.View
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
zIndex: 10,
height: headerHeight,
backgroundColor: 'lightblue'
}}
/>
);
};
export default AnimatedHeader;
without using the animation part its works properly but after adding animation I don't know why it's not working.

AsyncStorage not storing data and subsequently does not retrieve data

I am using expo and react-native
I am trying to use AsyncStorage to save 3 values in persistent storage
so I can get it from anywhere in the app,
but asyncstorage is not saving or retrieving,
I have rewritten the code several times and several diffrent ways and have tried a few tutorials, nothing works,
so here is the code for the page where i save the data (Login.js)
import React, { useState} from 'react'
import { View, Text,TextInput ,Button,SafeAreaView,Image,} from 'react-native'
import { ProgressDialog,Dialog } from 'react-native-simple-dialogs';
import AsyncStorage from '#react-native-community/async-storage';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
function Login ({navigation}){
const[alerted,isalerted]=useState(false)
const[authError,setAuthError]=useState(false)
const[accInactive,isAccInactive]=useState(false)
const[loginFail,didLoginFail]=useState(false)
const[login,didLogin]=useState(false)
const[email,setemail]=useState(email)
const[ClientID,setClientID]=useState(ClientID)
const[Password,setPassword]=useState(Password)
Here I am Trying to set the items for Asyncstorage
function LoginButton () {
AsyncStorage.setItem("MyEmail",email)
AsyncStorage.setItem("MyPassword",Password)
AsyncStorage.setItem("MyClientID",ClientID)
fetch('https://www.SITE.co.za/app-login.asp?ClientID='+ClientID+'&Username='+email+'&Pwd='+Password)
.then((response) => response.json())
.then((responseJson) => {
//Successful response from the API Call
if (JSON.stringify(responseJson).includes("Login Success")){
{isalerted(true),didLogin(false),isLoggedIn('Yes')}
}
else if (JSON.stringify(responseJson).includes("No Authentication Details Received"))
{
{setAuthError(true)}
}
else if (JSON.stringify(responseJson).includes("Account Not Active"))
{
{isAccInactive(true)}
}
else if (JSON.stringify(responseJson).includes("Login Details Incorrect"))
{
{didLoginFail(true)}
}
})
.catch((error) => {
console.error(error);
});
}
function navButton(){
navigation.navigate('Dashboard')
isalerted(false)
}
return (
<KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
<SafeAreaView>
<ProgressDialog
visible={didLogin}
activityIndicatorColor="#4994CF"
activityIndicatorSize="large"
animationType="slide"
title="Logging in"
message="Please, wait..."
/>
<Dialog
visible={alerted}
onTouchOutside={''} >
<View>
<Text style={{color:'green',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Success</Text>
<Button
title="Continue To Dashboard"
onPress={navButton}
/>
</View>
</Dialog>
<Dialog
visible={authError}
onTouchOutside={''} >
<View>
<Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>No Authentication Details Received</Text>
<Button
title="OK"
onPress={ ()=>setAuthError(false)}
/>
</View>
</Dialog>
<Dialog
visible={accInactive}
onTouchOutside={''} >
<View>
<Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Account Not Active</Text>
<Button
title="OK"
onPress={ () =>isAccInactive(false)}
/>
</View>
</Dialog>
<Dialog
visible={loginFail}
onTouchOutside={''} >
<View>
<Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Details Incorrect</Text>
<Button
title="OK"
onPress={()=> didLoginFail(false)}
/>
</View>
</Dialog>
<View style={{flexDirection:"row"}}>
<Image source={{uri: 'https://www.SITEe.co.za/images/smartpractice-logo-02.png'}}
style={{marginTop:35,paddingTop:10
, height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} />
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<View style={{width:'95%',alignContent:'center',marginLeft:10}}>
<Text style={{fontSize:20,color:'grey'}}>Welcome to the SmartPractice Beta App,
Please Login below with your SmartPractice login Details
</Text>
</View>
<View style={{marginTop:10,alignItems:"center"}}>
<View style={styles.Label}>
<Text style={styles.LabelText}>Email</Text>
</View>
<TextInput onChangeText={(text)=>setemail(text)} autoCompleteType='email' placeholder="Email" style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
<View style={styles.Label}>
<Text style={styles.LabelText}>Password</Text>
</View>
<TextInput onChangeText={(text)=>setPassword(text)} autoCompleteType="password" secureTextEntry={true} placeholder="Password" style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
<View style={styles.Label}>
<Text style={styles.LabelText}>ClientID</Text>
</View>
<TextInput onChangeText={(text)=>setClientID(text)} keyboardType="numeric" placeholder="ClientID" style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
<View style={{marginTop:5,width:'95%'}}>
<View style={{width:'95%',alignContent:'center',marginLeft:10,marginBottom:10}}>
<Text style={{fontSize:15,color:'grey'}}>ClientID : Log into Smartpractice on the internet and use the 4 digit number at the end of your URL (internet Address) of your login screen
</Text>
</View>
<Button
title="Save"
onPress={LoginButton}
/>
</View>
</View>
</SafeAreaView>
</KeyboardAwareScrollView>
);
}
const styles = {
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop:5
},
Label: {
backgroundColor:'#A6A5A4',
color:"white",
textAlign: "center",
marginTop:2,
fontSize: 15,
width:'100%',
},
alertmessage:{
color:'green'
},
LabelText: {
backgroundColor:'#A6A5A4',
color:"white",
textAlign: "center",
fontSize: 20,
},
};
export default Login;
The here is where I am trying to retrieve some of the data (Dashboard.js)
import React, {Component } from 'react'
import { View, Text,Image,TouchableOpacity,StyleSheet,SafeAreaView,} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import AsyncStorage from '#react-native-community/async-storage';
function Dashboard ({navigation}){
let MyClientID = AsyncStorage.getItem("MyClientID")
console.log(global.mail)
return (
<KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
<SafeAreaView style={styles.container}>
<View style={{flexDirection:"row"}}>
<Image source={{uri: 'https://www.site.co.za/images/smartpractice-logo-02.png'}}
style={{marginTop:5,paddingTop:10
, height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} />
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<Image source={{uri: 'https://www.site.co.za/images/logos/'+MyClientID+'/main-dashboard-logo.png'}}
style={{marginTop:5,paddingTop:10
, height: 70,width:'100%',flexWrap:'wrap',resizeMode:"contain",marginLeft:5 }} />
<View style={{justifyContent:"center", marginTop:6}}>
<Text style={styles.DateLabel}>Description</Text>
</View>
<TouchableOpacity style={styles.ImageButton}
onPress={() => navigation.navigate('Incidental Time')}
>
<Image style={{flexWrap:'wrap',resizeMode:"contain",maxHeight:120,maxWidth:120 }} tintColor='#4994CF' source={require('../../icons/time_log.png')} />
<Text style={styles.TextStyle}>Time Log</Text>
</TouchableOpacity>
</SafeAreaView>
</KeyboardAwareScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
textInput: {
backgroundColor:'#A6A5A4',
color:"white",
textAlign: "center",
marginTop:5,
fontSize: 20,
marginBottom:5
,marginLeft:1
},
DateLabel: {
backgroundColor:'#A6A5A4',
color:"white",
textAlign: "center",
marginTop:2,
fontSize: 20,
paddingLeft:140,
paddingRight:140,
width:'100%',
marginBottom:10
},
ImageButton: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
TextStyle:{
color:"grey"
}
});
export default Dashboard;
I have tried setting the items in a useeffect wrapping the values in the setitems in STRING()
tried making functions and const with async attached and the await before the set/getitem
I have check SO for hours and none of the answers or questions have helped me with this
I seriously dont know what I am doing wrong
I followed the asynstorage docs and even copying the code from the docs does not work
I dont get errors, Its been 2 days of struggling with something as simple as local storage
Please help
Both getItem and setItem of AsyncStorage are Promise so you need to use await or callback.
For setItem, current usage is okay but for getItem, it is essential.
You also need to use getItem in useEffect and make MyClientID as a state.
Try the following code instead of your Dashborad.js:
import React, {Component} from 'react';
import {
View,
Text,
Image,
TouchableOpacity,
StyleSheet,
SafeAreaView,
} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import AsyncStorage from '#react-native-community/async-storage';
function Dashboard({navigation}) {
const [MyClientID, setMyClientID] = useState('');
useEffect(() => {
AsyncStorage.getItem('MyClientID').then((myClientID) => {
setMyClientID(myClientID);
});
}, []);
console.log(global.mail);
return (
<KeyboardAwareScrollView keyboardShouldPersistTaps="handled">
<SafeAreaView style={styles.container}>
<View style={{flexDirection: 'row'}}>
<Image
source={{
uri: 'https://www.site.co.za/images/smartpractice-logo-02.png',
}}
style={{
marginTop: 5,
paddingTop: 10,
height: 80,
width: 360,
flexWrap: 'wrap',
resizeMode: 'contain',
}}
/>
<Text style={{textAlign: 'center', color: '#4994CF', marginTop: 35}}>
Beta
</Text>
</View>
<Image
source={{
uri:
'https://www.site.co.za/images/logos/' +
MyClientID +
'/main-dashboard-logo.png',
}}
style={{
marginTop: 5,
paddingTop: 10,
height: 70,
width: '100%',
flexWrap: 'wrap',
resizeMode: 'contain',
marginLeft: 5,
}}
/>
<View style={{justifyContent: 'center', marginTop: 6}}>
<Text style={styles.DateLabel}>Description</Text>
</View>
<TouchableOpacity
style={styles.ImageButton}
onPress={() => navigation.navigate('Incidental Time')}>
<Image
style={{
flexWrap: 'wrap',
resizeMode: 'contain',
maxHeight: 120,
maxWidth: 120,
}}
tintColor="#4994CF"
source={require('../../icons/time_log.png')}
/>
<Text style={styles.TextStyle}>Time Log</Text>
</TouchableOpacity>
</SafeAreaView>
</KeyboardAwareScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
textInput: {
backgroundColor: '#A6A5A4',
color: 'white',
textAlign: 'center',
marginTop: 5,
fontSize: 20,
marginBottom: 5,
marginLeft: 1,
},
DateLabel: {
backgroundColor: '#A6A5A4',
color: 'white',
textAlign: 'center',
marginTop: 2,
fontSize: 20,
paddingLeft: 140,
paddingRight: 140,
width: '100%',
marginBottom: 10,
},
ImageButton: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
TextStyle: {
color: 'grey',
},
});
export default Dashboard;
Not related to your Query but to be honest, based from my experience, Expo is the last thing you wanna use in your project. Especially if you'll be introducing Native dependencies later.
I know you can use ExpoKit then, but still... Don't use Expo
Instead of KeyboardAwareScrollView you can use Content from NativeBase.
For your query, all methods in AsyncStorage are Asynchronous. So remember to use await to get your values
async function fetchLocal(){
const persisted = await AsyncStorage.getItem("persisted");
if(persisted){
console.log(JSON.parse(persisted)); // Oh! the value for these persisted keys needs to be a string, so make sure to String()|.toString()|JSON.stringify objects you wanna serialize.
}
}

My React native app is going back to splash screen whenever i press a button with navigation function

I have made a splash screen by just placing an image and a setInterval() function, after that interval i have added the statement to navigate to login screen(navigation.navigate('loginScreen'), on login screen on a button(Signup button) i have added the fonPress() to navigate to signup screen(navigation.navigate('SignupScreen'). it works and the app goes to signup screen but the same setinterval function runs again and screen automatically navigates to login page again.
///////////////////////// App.js /////////////////////////////////
import 'react-native-gesture-handler';
import React from 'react';
import SplashScreen from './app/screens/splash.screen';
import LoginScreen from './app/screens/login.screen';
import SignupScreen from './app/screens/signup.screen';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Image,
ImageBackground,
} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { Header } from 'react-native/Libraries/NewAppScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="SplashScreen" headerMode='none' >
<Stack.Screen name="SplashScreen" component={SplashScreen} />
<Stack.Screen name="LoginScreen" component={LoginScreen} />
<Stack.Screen name="SignupScreen" component={SignupScreen}/>
</Stack.Navigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
});
export default App;
//////////////////////splash screen code///////////////////
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Image,
ImageBackground,
Button,
} from 'react-native';
function SplashScreen({ navigation }) {
//method to give splash screen effect ,screen navigates to next screen after 9000 milliseconds
setInterval(() => { navigation.navigate('LoginScreen')}, 9000);}
return (
<View style={styles.bod} >
<Text>{kaka}</Text>
<Image source={require("../../Images/ss1.jpg")} style={{flex:1,width:null, height: null}}/>
</View>
);
}
// const SplashScreen = () => {
// return (
// <View style={styles.bod}>
// <Image source={require("../../Images/ss1.jpg")} style={{width: '100%', height: '100%'}}/>
// <Button
// title="Go to Details"
// onPress={() => navigation.navigate('LoginScreen')}
// />
// </View>
// );
// };
const styles = StyleSheet.create({
bod : {
flex:1,
},
img:{
}
});
export default SplashScreen;
///////////Login Screen code//////////////////////
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Image,
ImageBackground,
Button,
} from 'react-native';
import { greaterThan } from 'react-native-reanimated';
import { TextInput } from 'react-native-gesture-handler';
function LoginScreen({ navigation }) {
return (
<View style={styles.grandparent}>
<View style={styles.welcom} >
<Text style={{color:'white',fontSize:35,fontFamily: "sans-serif-thin"}}>Welcome to CAWN!</Text>
</View>
<View style={styles.logo}>
<Image source={require("../../Images/logo2.png")} style={{width:'100%',height:'100%'}}/>
</View>
<View style={styles.mainlogin}>
<View style={styles.loginChild1}>
<Text style={{color:'white',fontSize:28,fontFamily:"sans-serif",paddingTop:4,}}>Member Sign In!</Text>
{/* <Image source={require("../../Images/user.png")} style={{width:'100%',height:'100%'}}/> */}
</View>
<View style={styles.fieldsMain}>
<View style={styles.userDiv}>
<View style={{flex: 1.5,width: 100,height: 53}}>
<Image source={require("../../Images/user.png")} style={{width:'100%',height:'100%'}}/>
</View>
<View style={{ flex: 5, width: 100,paddingLeft:4,}}>
<TextInput style={{ height: 48,backgroundColor:'white' }}></TextInput>
</View>
</View>
<View style={styles.psDiv}>
<View style={{flex: 1.5,width: 100,height: 53}}>
<Image source={require("../../Images/password1.png")} style={{width:'100%',height:'100%'}}/>
</View>
<View style={{ flex: 5, width: 100,paddingLeft:4,}}>
<TextInput style={{ height: 48,backgroundColor:'white', }}></TextInput>
</View>
</View>
<View style={{flex:0.3,}}></View>
</View>
<View style={styles.loginLastRow}>
<View style={styles.loginLastRowChild1}>
<Button title="Log in" color="#31b9eb" onPress={() => Alert.alert('Simple Button pressed')} />
</View>
<View style={styles.loginLastRowChild2}>
<View style={{paddingBottom:4,}}>
<Text style={{color:'white',fontSize:25,fontFamily: "sans-serif-thin",}}>Not a Member yet?</Text>
</View>
<Button title="Sign Up" color="#31b9eb" onPress={() => navigation.navigate('SignupScreen')} />
</View>
</View>
</View>
<View style={styles.lastSpace} />
</View>
);
}
const styles = StyleSheet.create({
grandparent : {
flex: 1,
width: '100%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
alignContent: 'center',
paddingHorizontal: 20,
paddingBottom: 30,
flexWrap: 'wrap',
//added by MFU
paddingTop:10,
backgroundColor:'#c3c8ed',
// borderWidth:1,
// borderColor:'red',
},
welcom : {
flex: 0.6,
width: '100%',
height: 100,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
alignContent: 'center',
// added by mfu
// borderWidth:1,
// borderColor:'green',
},
logo : {
flex: 1.9,
width: 250,
height: 100,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
alignContent: 'center',
// added by mfu
paddingTop:6,
// borderWidth:1,
// borderColor:'blue',
},
mainlogin : {
flex: 3.5,
width: 300,
height: 150,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
alignContent: 'center',
// borderWidth:3,
// borderColor:'black',
},
loginChild1 : {
flex: 0.4,
width: '100%',
height: 100,
flexWrap: 'wrap',
//added by MFU
alignItems: 'center',
alignContent: 'center',
// borderWidth:1,
// borderColor:'red',
},
fieldsMain : {
flex: 1.2,
width: '100%',
height: 100,
//added by mfu
alignItems: 'center',
// borderWidth:1,
// borderColor:'blue',
},
userDiv : {
flex: 1,
width: '80%',
// height: '100%',
//added by mfu
// borderWidth:1,
// borderColor:'green',
flexDirection: 'row',
},
psDiv : {
flex: 1,
width: '80%',
// height: 100,
//added by mfu
// borderWidth:1,
// borderColor:'pink',
flexDirection: 'row',
},
loginLastRow : {
flex: 1,
width: '80%',
height: 100,
//added by mfu
// borderWidth:1,
// borderColor:'purple',
},
loginLastRowChild1 : {
flex: 1,
width: 100,
height: 100,
// borderWidth:1,
// borderColor:'red',
},
loginLastRowChild2 : {
flex: 1,
width: '100%',
height: 100,
// borderWidth:1,
// borderColor:'green',
},
lastSpace : {
flex: 0.5,
width: 250,
height: 100,
// borderWidth:1,
// borderColor:'green',
},
});
export default LoginScreen;
setInterval runs the code repeatedly at the interval provided. I think you might want setTimeout (which will run just once)

React native app doesn`t fill the whole screen

I can't get my app to fill the whole screen. Whatever i do, there is always a white bar on the bottom of the page. It's so strange because it works on some devices but not others. i'm going crazy over this!
Ive tried const { height, width } = Dimensions.get('window'); and setting the app height with that, and it actually worked once, but now i can't get it to work again. ive tried rewrapping everything in different ways, with different views and scrollviews.
ps.: i removed all functions and useless code so it's not too much code, but
here is my code
import React, { Component } from 'react';
import {
View,
Switch,
Text,
TextInput,
TouchableOpacity,
ImageBackground,
Image,
Linking,
StatusBar,
Dimensions,
} from 'react-native';
import { ScaledSheet } from 'react-native-size-matters';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
export default class App extends Component {
constructor() {
super();
};
}
render() {
return (
<View style={styles.container}>
<KeyboardAwareScrollView
keyboardShouldPersistTaps={'always'}
style={styles.teste}
showsVerticalScrollIndicator={false}>
<StatusBar backgroundColor="#50a9f3" />
<ImageBackground source={require('./background.png')} style={styles.imagemBackground}>
<View style={styles.campos}>
<Image
style={{ width: 110, height: 110, alignSelf: 'center' }}
source={require('./logo.png')}
/>
<View style={styles.item}>
<Text style={styles.texto}>M²s do ambiente</Text>
<TextInput
style={styles.inputText}
keyboardType={'phone-pad'}
underlineColorAndroid={'white'}
onChangeText={mQuadrado => this.setState({ mQuadrado })}
/>
</View>
<View style={styles.item}>
<Text style={styles.texto}>Nº de pessoas</Text>
<TextInput
style={styles.inputText}
keyboardType={'phone-pad'}
underlineColorAndroid={'white'}
onChangeText={pessoas => this.setState({ pessoas })}
/>
</View>
<View style={styles.item}>
<Text style={styles.texto}>Nº de eletrodomésticos</Text>
<TextInput
style={styles.inputText}
keyboardType={'phone-pad'}
underlineColorAndroid={'white'}
onChangeText={eqps => this.setState({ eqps })}
/>
</View>
<View style={styles.item}>
<Text style={styles.texto}>Nº de janelas </Text>
<TextInput
style={styles.inputText}
keyboardType={'phone-pad'}
underlineColorAndroid={'white'}
onChangeText={jnls => this.setState({ jnls })}
/>
</View>
<View style={styles.switch}>
<Text style={styles.texto}>Recebe luz solar </Text>
<Switch
style={{ transform: [{ scaleX: 0.9 }, { scaleY: 0.9 }] }}
thumbColor="#ffffff"
trackColor={{ true: '#c0c0c0' }}
value={this.state.switch}
onValueChange={value => this.setState({ switch: value })}
/>
</View>
<View style={styles.input}>
<TouchableOpacity style={styles.opacity} onPress={this.calcular}>
<Text style={styles.textoCalcular}>CALCULAR</Text>
</TouchableOpacity>
</View>
<View style={styles.resultadoBox}>
<Text style={styles.textoResultado}>Você precisará de</Text>
<Text style={styles.resultado}>{btu == '0' ? null : btu + '.000 BTUS'}</Text>
</View>
</View>
<View style={styles.banner}>
<TouchableOpacity
style={styles.bannerContainer}
onPress={() => Linking.openURL('https://matum.com.br/produtos-sisum/')}>
<Text style={styles.bannerTexto}>Gerencie suas manutenções preventivas e corretivas</Text>
<Text style={styles.bannerTexto}>Relatório PMOC simples</Text>
<Text style={styles.bannerTextoX}>Saiba mais</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</KeyboardAwareScrollView>
</View>
);
}
}
const { height, width } = Dimensions.get('window');
const heightCerto = height - StatusBar.currentHeight;
const styles = ScaledSheet.create({
container: {
flex: 1,
},
teste: {
flex: 1,
},
imagemBackground: {
flex: 1,
},
campos: {
flex: 95,
justifyContent: 'flex-start',
alignItems: 'stretch',
padding: '20#s',
paddingTop: '12#s',
},
item: {
flex: 1,
},
switch: {
paddingTop: '15#s',
flexDirection: 'row',
justifyContent: 'flex-start',
flex: 1,
},
textoCalcular: {
fontSize: '15#s',
color: '#ffffff',
textShadowColor: 'black',
textShadowRadius: 2,
},
input: {
padding: '20#s',
alignItems: 'center',
flex: 1,
},
opacity: {
backgroundColor: '#50a9f3',
borderWidth: '1.5#s',
borderRadius: '10#s',
borderColor: '#000000',
width: '190#s',
height: '39#s',
justifyContent: 'center',
alignItems: 'center',
},
resultadoBox: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(100,100,100,0.5)',
margin: 0,
borderColor: 'rgba(100,100,100,0.5)',
borderRadius: '10#s',
},
resultado: {
fontSize: '28#s',
color: 'white',
textShadowColor: 'black',
textShadowRadius: 5,
},
banner: {
flex: 10,
backgroundColor: 'rgba(140,140,140,0.5)',
margin: 0,
borderColor: '#50a9f3',
borderWidth: '1.5#s',
borderRadius: '10#s',
alignSelf: 'stretch',
},
bannerContainer: {
alignItems: 'center',
},
bannerTexto: {
color: '#ffffff',
fontSize: '12#s',
},
bannerTextoX: {
color: '#50a9f3',
fontSize: '10#s',
textShadowColor: 'black',
textShadowRadius: 4,
},
inputText: {
fontSize: '12#s',
color: 'white',
textShadowColor: 'black',
textShadowRadius: 5,
height: '38#s',
},
texto: {
fontSize: '13#s',
color: '#ffffff',
textShadowColor: 'black',
textShadowRadius: 5,
},
textoResultado: {
fontSize: '16#s',
color: 'white',
textShadowColor: 'black',
textShadowRadius: 5,
},
});
I think you're talking about the image background but not totally sure. I was able to get it to stretch to the full height by adding the following height declaration:
imagemBackground: {
flex: 1,
height: height,
},
link to example: https://snack.expo.io/r1Y-zpwMH
You are using flex:1 many times in style that is the problem.
please give flex:1 in container style and remove all flex:1 in other styles instead of flex:1 you can use width and height in percentage.
like style={{width:'100%',height:'40%'}}.
Thank you!

Resources