component is not defined react native - react-native-ios

I have created a empty page and trying to import the component of another page into the empty one.
App.js
import React, {Component} from 'react';
import {name as appName} from './app.json';
import {
View,
Text,
StyleSheet,
TextInput,
Button,
TouchableOpacity,
AppRegistry
} from 'react-native';
import Login from "./Login";
function validate() {
alert("Button Clicked...")
console.log("Hello world!")
}
export default class App extends Component{
render(){
return(
<Login />
);
}
}
const styles = StyleSheet.create({
container: {
// justifyContent: 'center',
// alignItems: 'center',
backgroundColor: '#af522a',
flex: 1
},
txtText: {
textAlign: 'center',
fontSize: 25,
color: '#9daf2a'
},
txtInput: {
height: 45,
borderColor: '#9daf2a',
borderWidth: 3,
marginTop: 75,
padding: 12,
backgroundColor: '#FFFFFF',
marginLeft: 16,
marginRight: 16,
borderRadius: 15
},
txtInput2: {
height: 45,
borderColor: '#9daf2a',
borderWidth: 3,
padding: 12,
backgroundColor: '#FFFFFF',
marginLeft: 16,
marginRight: 16,
marginTop: 24,
borderRadius: 15
},
loginScreenButton:{
marginRight:40,
marginLeft:40,
marginTop:45,
paddingTop:10,
paddingBottom:10,
backgroundColor:'#593eb2',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
loginText:{
color:'#fff',
textAlign:'center',
paddingLeft : 10,
paddingRight : 10
}
})
Login.js
import React, {component} from 'react';
import{
View,
TextInput,
StyleSheet
}from 'react-native';
export default class Login extends Component {
render(){
return(
<View style = {styles.container}>
</View>
)
}
}
const styles = StyleSheet.create({
container: {background: "#44c41d", flex: 1}
})
Error
I have just started up with react-native and don't have that much of knowledge . so, please tell me if any one have any solution.
Thanks in advance.

in your Login.js, you use lowercase component,
import React, {component} from 'react'
convert it to uppercase.
import React, {Component} from 'react';

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',
},
});

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.

PropTypes is deprecated and how to solve it

i am getting the error
Undefined is not an object (Evaluating '_react2.PropTypes.string')
While googling I found out that React.Proptypes is deprecated and it's on its own.
But, How can I solve this issue ?
I tried the following:
1.) npm install -g prop-types --save
2.) part from the code
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Text, View, TouchableOpacity } from 'react-native';
import { Actions } from 'react-native-router-flux';
import { Field, reduxForm } from 'redux-form';
import { Container, Input, Button, Item, Spinner } from '../common';
import styles from './authStyle';
const propTypes = {
handleSubmit: PropTypes.func.isRequired,
clearState: PropTypes.func.isRequired,
signUpUser: PropTypes.func.isRequired,
authError: PropTypes.string.isRequired,
loading: PropTypes.bool.isRequired,
};
class Signup extends Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
...
However, I end up having the same error and how can I solve it?
UPDATE
import React from 'react';
import PropTypes from 'prop-types';
import { Text, TouchableOpacity } from 'react-native';
const propTypes = {
children: PropTypes.node.isRequired,
onPress: PropTypes.func.isRequired,
buttonStyle: PropTypes.object,
textStyle: PropTypes.object,
};
const defaultProps = {
buttonStyle: {},
textStyle: {},
};
function Button({ onPress, children, buttonStyle, textStyle }) {
const { button, text } = styles;
return (
<TouchableOpacity
onPress={onPress}
style={[button, buttonStyle]}
>
<Text style={[text, textStyle]}>
{children}
</Text>
</TouchableOpacity>
);
}
const styles = {
button: {
flex: 1,
alignSelf: 'stretch',
backgroundColor: '#039be5',
borderRadius: 3,
marginTop: 10,
},
text: {
alignSelf: 'center',
color: '#fff',
fontSize: 16,
fontWeight: '600',
paddingTop: 10,
paddingBottom: 10,
},
};
Button.defaultProps = defaultProps;
Button.propTypes = propTypes;
export { Button };
Use this instead
import PropTypes from 'prop-types';
Button.propTypes = {
type: PropTypes.string
};

React-Native style a sticky header when it sticks

I've a short question: How can I apply a different style to a sticky header in a scrollview when it sticks?
I wanna add some shadow/elevation when it sticks.
Thank you :)
Environment
react-native: 0.45.0
Currently React Native ScrollView component has a property called stickyHeaderIndices, even in your 0.45 version. You can use it to pass your header child index that should be sticky. After that you can use onScroll event to get current scroll position and when achieve your header size add a custom style with shadow. See for the example here:
https://snack.expo.io/#fabiodamasceno/scroll-sticky-styled
or if you prefer:
import * as React from 'react';
import { Text, View, ScrollView } from 'react-native';
const HEADER_HEIGHT = 20;
const headerStyle = {
backgroundColor: '#e5e5e5',
height: HEADER_HEIGHT
}
const myShadowStyle = {
elevation: 3,
shadowOpacity: 0.2,
shadowRadius: 6,
shadowOffset: {
height: 3,
width: 0,
},
};
export default class App extends React.Component {
state = {
headerStyle : {
...headerStyle
}
}
render() {
return (
<View style={{marginTop: HEADER_HEIGHT, height: 150}}>
<ScrollView
stickyHeaderIndices={[0]}
onScroll={event => {
const y = event.nativeEvent.contentOffset.y;
if(y >= HEADER_HEIGHT)
this.setState({
headerStyle:{
...headerStyle,
...myShadowStyle
}
})
else
this.setState({
headerStyle:{
...headerStyle,
}
})
}}
>
<View style={this.state.headerStyle}>
<Text>My Header Title</Text>
</View>
<Text>Item 1</Text>
<Text>Item 2</Text>
<Text>Item 3</Text>
<Text>Item 4</Text>
<Text>Item 5</Text>
<Text>Item 6</Text>
<Text>Item 7</Text>
<Text>Item 8</Text>
<Text>Item 9</Text>
<Text>Item 10</Text>
<Text>Item 11</Text>
<Text>Item 12</Text>
<Text>Item 13</Text>
<Text>Item 14</Text>
</ScrollView>
</View>
);
}
}
Thnx me later..! The final code should be looking like this. This is the most basic example that we can have to dig into animations using react-native.
import React, { useRef } from "react";
import {
SafeAreaView,
StyleSheet,
Text,
Dimensions,
Animated,
View,
} from "react-native";
import Colors from "../../../../config/color/color";
const App = () => {
const scrollPosition = useRef(new Animated.Value(0)).current;
const minHeaderHeight = 70;
const maxHeaderHeight = 200;
const headerHeight = scrollPosition.interpolate({
inputRange: [0, 500],
outputRange: [maxHeaderHeight, minHeaderHeight],
extrapolate: "clamp",
});
const opacity = scrollPosition.interpolate({
inputRange: [0, 100, 200],
outputRange: [1, 0.5, 0],
extrapolate: "clamp",
});
const size = scrollPosition.interpolate({
inputRange: [0, 100, 200, 300, 400],
outputRange: [20, 17, 15, 13, 11],
extrapolate: "clamp",
});
const imageHeight = scrollPosition.interpolate({
inputRange: [0, 400],
outputRange: [100, 50],
extrapolateLeft: "identity",
extrapolateRight: "clamp",
});
const imagePosition = scrollPosition.interpolate({
inputRange: [0, 400],
outputRange: [(37 * Dimensions.get("window").width) / 100, 0],
extrapolateLeft: "identity",
extrapolateRight: "clamp",
});
return (
<SafeAreaView>
<View>
<Animated.View
style={{
// position: 'absolute',
top: 0,
left: 0,
right: 0,
zIndex: 10,
height: headerHeight,
backgroundColor: "lightblue",
}}
>
<Animated.Text
style={{
opacity: opacity,
fontSize: size,
}}
>
Header
</Animated.Text>
<Animated.Image
style={{
height: imageHeight,
width: imageHeight,
borderRadius: imageHeight,
transform: [{ translateX: imagePosition }],
}}
source={{
uri: "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png",
}}
/>
</Animated.View>
<Animated.ScrollView
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollPosition } } }],
{ useNativeDriver: false }
)}
contentInsetAdjustmentBehavior="automatic"
style={[styles.scrollView]}
>
{Array.from(Array(100), (e, key) => {
return <Text key={key}>Item {key}</Text>;
})}
</Animated.ScrollView>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
});
export default App;

Resources