Positioning item at the bottom of the screen in React Native - flexbox

I want to place my svg at the bottom of the screen. I have tried flex properties and postion absolute (bottom:0) but svg doesn't go to the bottom of the screen, and when I give the absolute position of svg it disappears while zIndex also doesn't work. Here is my code.
here is snack.snack
import Otp from '../assets/otp2.svg';
import Waves from '../assets/waves.svg';
const windowHeight = Dimensions.get('window').height;
const SignUp = () => {
return (
<View style={styles.container}>
<View style={styles.section1}>
<View
style={{
// justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
}}>
<Icon size={40} color="white" name="west" />
<Text style={styles.otpText}>OTP Verification</Text>
</View>
<Otp style={{marginBottom: 40}} />
</View>
<View style={styles.section2}>
{/* <View style={styles.section3}></View> */}
<View style={styles.wave}>
<Waves />
</View>
</View>
</View>
);
};
export default SignUp;
const styles = StyleSheet.create({
container: {
flex: 1,
},
section1: {
flex: 1,
backgroundColor: '#f07279',
justifyContent: 'space-evenly',
alignItems: 'center',
},
section2: {
flex: 1,
backgroundColor: '#fff',
// alignContent: 'flex-end',
// alignItems: 'flex-end',
},
section3: {
flex: 1,
backgroundColor: 'grey',
width: '80%',
height: '80%',
borderRadius: 25,
// position: 'absolute',
// zIndex: 1,
// top: -40,
},
otpText: {
fontSize: 25,
color: '#ffffff',
width: 200,
fontFamily: 'sans-serif-light',
},
wave: {
flex: 1,
// position: 'absolute',
// bottom: 0,
width: '100%',
// zIndex: 5,
// marginTop: '67%',
},
});
and here is the reference what i want to do.

Related

React Native Paper - Font Family not take effect in theme

Version:
"react-native": "0.68.2",
"react-native-paper": "5.0.0-rc.3",
"react-native-vector-icons": "^9.2.0",
Problem: the fontFamily in the
<Text variant="displayLarge" theme={{ typescale: { displayLarge: { fontSize: 30, fontFamily: 'HelveticaNeue-Thin' },},}}> does not take effect while the <Text style={theme.fonts.thin}> does works as expected.
https://snack.expo.dev/#wztrustgrid/fontfamilyintheme
import { StyleSheet, View } from 'react-native';
import {
configureFonts,
Provider as PaperProvider,
MD3LightTheme as DefaultTheme,
Text,
} from 'react-native-paper';
const fontConfig = {
ios: {
thin: {
fontFamily: 'HelveticaNeue-Thin',
fontSize: 30,
},
},
};
const theme = {
...DefaultTheme,
fonts: configureFonts(fontConfig),
};
export default function App() {
return (
<PaperProvider
theme={theme}
>
<View style={styles.container}>
{/* Display correct font */}
<Text style={theme.fonts.thin}>
ABCDEFGHIJKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz 1234567890
</Text>
{/* Display incorrect font */}
<Text
variant="displayLarge"
theme={{
typescale: {
displayLarge: { fontSize: 30, fontFamily: 'HelveticaNeue-Thin' },
},
}}
>
ABCDEFGHIJKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz 1234567890
</Text>
</View>
</PaperProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

how to post array of multiple object in react native

**how to pass array of multiple object in database react native . i aslo tried axios fetch and redux but its not responding **
import React, { useState, useEffect, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity, ScrollView, Dimensions } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import _ from "lodash"
import ClassSectionFilter from '../singleStudentAttendance/ClassSectionFilter';
import { CheckBox } from 'react-native-elements';
import { useIsFocused } from "#react-navigation/native";
import { useRegisterTechAttendanceMutation } from '../../../services/userAuthApi';
import Toast from "react-native-toast-message";
import axios from 'axios'
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const MarkAttendanceScreen = ({ navigation, route }) => {
const [columns, setColumns] = useState([
"RollNo",
"Name",
])
const [direction, setDirection] = useState('')
const [selectedColumn, setSelectedColumn] = useState('')
const [ teachers , setTeachers] = useState([]);
const [ attendance, setAttendance ] = useState()
const [ attendanceState, setAttendanceState ] = useState('')
const fetchData = async () => {
const resp = await fetch(`http://192.168.18.64:8000/api/user/getSometeacher/${route.params.schoolId}`);
const data = await resp.json();
const schAdminId = (data.map(l => l._id ? { ...l, schoolAdminID: route.params.schoolAdminID } : l));
setAttendanceState(schAdminId)
};
const focus = useIsFocused();
useLayoutEffect(()=>{
fetchData();
}, [focus])
const MarkAttendance = (item, S) => {
const attend = (attendanceState.map(l => l._id === item._id ? { ...l, attendance: S } : l));
setAttendanceState(attend)
setAttendance(attend)
}
const [items, setItems] = useState()
const sortTable = (column) => {
const newDirection = direction === "desc" ? "asc" : "desc"
const sortedData = _.orderBy(teachers, [column], [newDirection])
setSelectedColumn(column)
setDirection(newDirection)
setTeachers(sortedData)
}
const [registerTechAttendance] = useRegisterTechAttendanceMutation();
const handleFormSubmit = async () => {
const bodyFormData = new FormData();
attendance.forEach((item) => {
bodyFormData.append('attendance', item);
});
const res = axios.post('http://192.168.18.64:8000/api/user/teacherattendance', bodyFormData)
if (res.data.status === "success") {
navigation.navigate("SchoolAdminHomePage");
}
if (res.data.status === "failed") {
Toast.show({
type: "warning",
position: "top",
topOffset: 0,
text1: res.data.message,
});
}
};
// const onSubmit = () => {
// const formData = new FormData()
// formData.append(attendance);
// console.log(formData)
// fetch('http://192.168.18.64:8000/api/user/teacherattendance', {
// method: "POST",
// body: JSON.stringify(formData),
// headers: {
// 'content-type': 'application/json',
// }
// })
// .then((response) => console.log(response))
// .catch(err => {
// console.log(err);
// })
// }
const tableHeader = () => (
<View style={styles.tableHeader} >
{
columns.map((column, index) => {
{
return (
<TouchableOpacity
key={index}
style={styles.columnHeader}
onPress={() => sortTable(column)}>
<Text style={styles.columnHeaderTxt}>{column + ""}
{selectedColumn === column && <MaterialCommunityIcons
name={direction === "desc" ? "arrow-down-drop-circle" : "arrow-up-drop-circle"}
/>
}
</Text>
</TouchableOpacity>
)
}
})
}
</View>
)
return (
<View style={{ height: windowHeight, width: '100%' }}>
<View >
<ClassSectionFilter />
</View>
<FlatList
data={attendanceState}
keyExtractor={(item, index) => index + ""}
style={{ maxWidth: '100%' }}
ListHeaderComponent={tableHeader}
stickyHeaderIndices={[0]}
extraData={attendanceState}
renderItem={({ item, index }) => {
return (
<View style={{ ...styles.tableRow, backgroundColor: index % 2 == 1 ? "#F0FBFC" : "white", width: '100%', }}>
<Text style={{ ...styles.columnRowTxt, fontWeight: "bold" }}>{item.roll_no}</Text>
<Text style={{ ...styles.columnRowTxt }}>{item.first_name}</Text>
<ScrollView horizontal={true}
showsHorizontalScrollIndicator={true}
pagingEnabled={true}
style={{ width: '150%' }}
>
<View style={{ flexDirection: 'row', left: 40 }}>
<View
style={{
left: 23
}}
>
<CheckBox
title='P'
checkedColor='green'
checked={item.attendance === 'P' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'P')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="green"
unfillColor="#FFFFFF"
text="P"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkPresent()}
isChecked={false}
/> */}
</View>
<View style={{
left: 5
}}>
<CheckBox
title='A'
checkedColor='red'
checked={item.attendance === 'A' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'A')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="red"
unfillColor="#FFFFFF"
text="A"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkAbsent()}
/> */}
</View>
<View style={{
left: 5,
}}>
<CheckBox
title='L'
checkedColor='gray'
checked={item.attendance === 'L' ? true : false}
checkedIcon='dot-circle-o'
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'L')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 70,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent',
}}
/>
</View>
</View>
</ScrollView>
</View>
)
}}
/>
<View>
<TouchableOpacity
onPress={handleFormSubmit}
style={{
justifyContent: "center",
alignItems: "center",
padding: 15,
width: "100%",
marginVertical: 5,
borderRadius: 50,
marginBottom: 60,
fontWeight: "bold",
backgroundColor: "#5062BD",
elevation: 1,
marginTop: 30,
bottom:20,
}}
>
<Text
style={{
color: "white",
justifyContent: "center",
alignItems: "center",
}}
>
Submit Attendance
</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
tableHeader: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#5062BD",
borderTopEndRadius: 10,
borderTopStartRadius: 10,
height: 50,
},
tableRow: {
flexDirection: "row",
height: 40,
margin: 2,
left: 8
},
columnHeader: {
width: "16%",
justifyContent: "center",
alignItems: "flex-start",
margin: 10
},
columnHeaderTxt: {
color: "white",
fontWeight: "bold",
},
columnRowTxt: {
width: "18%",
}
});
export default MarkAttendanceScreen
data also show in my console but it is not posting. i am also trying redux, fetch and axios method but its not give me a solution
enter image description here

Can't find variable setUserEmail

I'm linking my backend with my frontend in react native and I get this error Can't find-variable: setUserEmail when I go to type in an email into the TextInput. I'm working on the login page and use a fetch API to log the user into the app. I followed a tutorial to the point but I'm getting this error each time I try to enter an email, I get a message say setUserEmail is declared but never used. Any help would be greately appreciated
import React, { Component, useState, createRef } from 'react';
import { StyleSheet, Text, TextInput, View, Dimensions, StatusBar, TouchableOpacity,Keyboard } from 'react-native';
export default function Login(){
const [userEmail, setUserEmail] = useState('');
const [userPassword, setUserPassword] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmitPress = () => {
setLoading(true);
let dataToSend = {userEmail: userEmail, password: userPassword};
let formBody = [];
for (let key in dataToSend) {
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
fetch('http://localhost:3000/users/users', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
body: JSON.stringify({
userEmail: userEmail,
password: userPassword,
os: Platform.OS === "ios" ? "iOS" : "Android",
}),
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
AsyncStorage.setItem('user_id', responseJson.data.email);
console.log(responseJson.data.email);
navigation.replace('DrawerNavigationRoutes');
} else {
setErrortext(responseJson.msg);
console.log('Please check your email id or password');
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
}
return(
<View style={style.container}>
<View style={style.parent}>
<Text style={style.title}>Login</Text>
<Text style={style.heading}>Please Sign in to continue</Text>
</View>
<View style={style.root}>
<TextInput name='txtEmail' placeholder='someone#something.com' style={style.email} onChangeText={(UserEmail) => setUserEmail(UserEmail)}/>
<TextInput type='password' name='txtPassword' placeholder='Password' secureTextEntry={true} style={style.password} onChangeText={(UserPassword) => setUserPassword(UserPassword)}/>
<Text style={style.forgotpassword}>Forgot Password?</Text>
<TouchableOpacity
title="Login"
style={style.login}
onPress={handleSubmitPress()}>
<Text style={style.login_caption}>Login </Text>
</TouchableOpacity>
</View>
<StatusBar hidden />
</View>
);
}
const style = StyleSheet.create({
container:{
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
forgotpassword:{
textAlign: 'right',
marginTop: 10,
},
login:{
width: 150,
height: 45,
backgroundColor: '#FFB900',
position: 'absolute',
right: 0,
marginLeft: 25,
marginRight: 15,
marginTop: 150,
borderRadius: 25,
},
login_caption:{
color: '#fff',
textAlign: 'left',
paddingLeft: 15,
justifyContent: 'center',
paddingTop: 12,
},
parent:{
marginTop: 85,
},
title:{
fontSize: 36,
fontWeight: "900",
paddingLeft: 25,
},
heading:{
color: '#C0C0C0',
paddingLeft: 25,
},
root:{
width: 250,
height: 350,
marginTop: 85,
alignSelf: 'center',
},
email:{
width: 275,
height:38,
borderColor: "#111",
borderWidth: 1,
fontSize: 16,
paddingLeft:10,
justifyContent: 'center',
borderRadius: 15,
alignSelf: 'center',
},
password:{
width: 275,
height:38,
borderColor: "#111",
alignSelf: 'center',
borderWidth: 1,
fontSize: 16,
paddingLeft:10,
justifyContent: 'center',
marginTop: 15,
borderRadius: 15,
}
});
UPDATED WITH CHANGES
With a little bit of cleaning, that what I ended up with:
import AsyncStorage from "#react-native-community/async-storage";
import React, { useState } from "react";
import { Dimensions, Platform, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";
const Login = () => {
const [userEmail, setUserEmail] = useState("");
const [userPassword, setUserPassword] = useState("");
const [errorText, setErrorText] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmitPress = () => {
setLoading(true);
const dataToSend = { userEmail: userEmail, password: userPassword };
let formBody = [];
for (const key in dataToSend) {
const encodedKey = encodeURIComponent(key);
const encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch("http://localhost:3000/users/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
body: JSON.stringify({
userEmail: userEmail,
password: userPassword,
os: Platform.OS === "ios" ? "iOS" : "Android",
}),
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === "success") {
AsyncStorage.setItem("user_id", responseJson.data.email);
console.log(responseJson.data.email);
// navigation.replace('DrawerNavigationRoutes');
} else {
setErrorText(responseJson.msg);
console.log("Please check your email id or password");
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
};
return (
<View style={styles.container}>
<View style={styles.parent}>
<Text style={styles.title}>Login</Text>
<Text style={styles.heading}>Please Sign in to continue</Text>
</View>
<View style={styles.root}>
<TextInput
name="txtEmail"
placeholder="someone#something.com"
style={styles.email}
onChangeText={(UserEmail) => setUserEmail(UserEmail)}
/>
<TextInput
type="password"
name="txtPassword"
placeholder="Password"
secureTextEntry={true}
style={styles.password}
onChangeText={(UserPassword) => setUserPassword(UserPassword)}
/>
<Text style={styles.forgotpassword}>Forgot Password?</Text>
<TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress}>
<Text style={styles.login_caption}>Login </Text>
</TouchableOpacity>
</View>
<StatusBar hidden />
</View>
);
};
const styles = StyleSheet.create({
container: {
height: Dimensions.get("window").height,
width: Dimensions.get("window").width,
},
email: {
alignSelf: "center",
borderColor: "#111",
borderRadius: 15,
borderWidth: 1,
fontSize: 16,
height: 38,
justifyContent: "center",
paddingLeft: 10,
width: 275,
},
forgotpassword: {
marginTop: 10,
textAlign: "right",
},
heading: {
color: "#C0C0C0",
paddingLeft: 25,
},
login: {
backgroundColor: "#FFB900",
borderRadius: 25,
height: 45,
marginLeft: 25,
marginRight: 15,
marginTop: 150,
position: "absolute",
right: 0,
width: 150,
},
login_caption: {
color: "#fff",
justifyContent: "center",
paddingLeft: 15,
paddingTop: 12,
textAlign: "left",
},
parent: {
marginTop: 85,
},
password: {
alignSelf: "center",
borderColor: "#111",
borderRadius: 15,
borderWidth: 1,
fontSize: 16,
height: 38,
justifyContent: "center",
marginTop: 15,
paddingLeft: 10,
width: 275,
},
root: {
alignSelf: "center",
height: 350,
marginTop: 85,
width: 250,
},
title: {
fontSize: 36,
fontWeight: "900",
paddingLeft: 25,
},
});
export default Login;
There were few mistakes in your code,
you used setErrorText without declaring it.
this line <TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress()}> was not good, maybe it was the cause of infinite rendering.
I solved all those errors very easily by using some extension in my IDE to clean code automatically like prettier and ESLint, and I used typescript. I really suggests that you do the same.

React Native Navigation: Drawer items not showing or disappearing when setting a flex value

Following is my minimal working example. It is 3 basic screens, and a Drawer screen. In the render() method of the DrawerScreen I am populating the drawer screen with the navigation items from the tabs array.
When I set the flex value of the navigationItem everything starts to behave weirdly.
The items don't show up in the drawer screen when reloading the app most of the time
When the items do show up, they disappear after they have been tapped on.
If the navigationItem style in the Stylesheet has no flex value, it works as expected. I don't understand what is happening and have no idea how to fix this.
Code:
const packageName = 'com.rnplayground';
class FirstTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>FirstTab</Text>
</View>
)
};
}
class SecondTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>SecondTab</Text>
</View>
)
};
}
class ThirdTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>ThirdTab</Text>
</View>
)
};
}
class DrawerScreen extends React.Component {
render(){
const {tabs} = this.props;
return(
<View style={styles.navigationContainer}>
{tabs.map((route, index) => {
const navigationLabel = route.title;
return (
<TouchableHighlight
key={route.screen}
onPress={() => {
this.props.navigator.switchToTab({
tabIndex: index
});
}}
underlayColor='blue'
>
<View style={styles.navigationItem}>
<Text style={styles.navigationLabel}>
{navigationLabel}
</Text>
</View>
</TouchableHighlight>
);
})}
</View>
)
};
}
function registerScreens(){
Navigation.registerComponent(`${packageName}.FirstTab`, () => FirstTab );
Navigation.registerComponent(`${packageName}.SecondTab`, () => SecondTab );
Navigation.registerComponent(`${packageName}.ThirdTab`, () => ThirdTab );
Navigation.registerComponent(`${packageName}.DrawerScreen`, () => DrawerScreen );
}
function startApp() {
registerScreens();
const tabs = [
{
screen: `${packageName}.FirstTab`,
title: 'FirstTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
{
screen: `${packageName}.SecondTab`,
title: 'SecondTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
{
screen: `${packageName}.ThirdTab`,
title: 'ThirdTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
];
Navigation.startTabBasedApp(
{
tabs: tabs,
drawer: {
left: {
screen: `${packageName}.DrawerScreen`,
passProps: {
tabs: tabs
},
fixedWidth: 800,
}
},
tabsStyle:{
tabBarHidden: true,
}
},
);
}
startApp();
Stylesheet:
const styles = StyleSheet.create({
navigationContainer:{
flex: 1,
width: '100%',
backgroundColor: 'white',
},
navigationItem: {
flex: 1,
}
});
Here is an imgur link showing the behavior in question.

Center an item, then have an item to the left - Flexbox React Native

Using flexbox in React Native I'm having a lot of trouble trying to do the following seemingly simple task:
I have two item inside a container. I want one centered, and the other one to lie directly to the left of it.
You can change the flex size properties of the two outer components, and as long as they are the same, the middle item will be centered.
Notice the justifyContent:'flex-end' property of the first component. This styling is what is making the item lie directly to the left of the middle item.
<View style={styles.container}>
<View style={styles.component1}>
<Text>Right</Text>
</View>
<View style={styles.component2}>
<Text style={{ textAlign:'center' }}>I am the Center Component</Text>
</View>
<View style={styles.component3}></View>
</View>
container: {
flexDirection:'row',
flex:1,
marginTop:60
},
component1: {
flex:1,
flexDirection: 'row',
justifyContent: 'flex-end',
height:80
},
component2: {
flex:1,
height:80,
backgroundColor: 'red',
justifyContent:'center'
},
component3: {
flex:1,
}
Also, the entire code is below:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.component1}>
<Text>Right</Text>
</View>
<View style={styles.component2}>
<Text style={{ textAlign:'center' }}>I am the Center Component</Text>
</View>
<View style={styles.component3}></View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flexDirection:'row',
flex:1,
marginTop:60
},
component1: {
flex:1,
flexDirection: 'row',
justifyContent: 'flex-end',
height:80
},
component2: {
flex:1,
height:80,
backgroundColor: 'red',
justifyContent:'center'
},
component3: {
flex:1,
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);

Resources