About this.state function in React Native App - react-native

Hello this is my code. When I try to fill the text box then the error come i.e. ('this.setState is not a function.(In this.setState({emal:email)} this.setState is underfined').
Here is my code:
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
TextInput,
TouchableHighlight,
Alert,
} from 'react-native';
export default function LoginScreen() {
onClickListener = (viewId) => {
Alert.alert("Alert", "You can't "+viewId);
}
return (
https://png.icons8.com/message/ultraviolet/50/3498db'}}/>
this.setState({email})}/>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({password})}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.onClickListener('login')}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonContainer} onPress={() => this.onClickListener('restore_password')}>
<Text>Forgot your password?</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonContainer} onPress={() => this.onClickListener('register')}>
<Text>Register</Text>
</TouchableHighlight>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#DCDCDC',
},
inputContainer: {
borderBottomColor: '#F5FCFF',
backgroundColor: '#FFFFFF',
borderRadius:30,
borderBottomWidth: 1,
width:250,
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center'
},
inputs:{
height:45,
marginLeft:16,
borderBottomColor: '#FFFFFF',
flex:1,
},
inputIcon:{
width:30,
height:30,
marginLeft:15,
justifyContent: 'center'
},
buttonContainer: {
height:45,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:20,
width:250,
borderRadius:30,
},
loginButton: {
backgroundColor: "#00b5ec",
},
loginText: {
color: 'white',
}
});

That is the problem
export default function LoginScreen()
Change it to the
export default class LoginScreen extends Component

For using state, it must a stateful component rather than stateless component, So you have to change your functional component into Class.
change
export default function LoginScreen()
to
export default class LoginScreen extends React.Component

In react-native setState function has syntax
this.setState({someField:someValue})
you are using wrong syntax there, you have to give state name and value
this.setState({email})
this.setState({password})
these line should be like -
this.setState({ email: value })
this.setState({password: value })

if you want to use functional components you can use the UseState hook like this
by importing and initializing the state as shown below:
import React,{useState} from 'react';
export default function LoginScreen() {
const [email,setEmail]=useState(initialValues);
//setEmail function can be used for changing the state
}
use can see the usage of the useState here [https://reactjs.org/docs/hooks-state.html]
hope this helps for you

if you want to use functional components use react hooks,
otherwise use class component as below.
import React, { Component } from 'react';
import { Image, StyleSheet, Text, View, TextInput, TouchableHighlight, Alert } from 'react-native';
export default class LoginScreen extends Component {
onClickListener = viewId => {
Alert.alert('Alert', "You can't " + viewId);
};
render() {
return (
<View>
<View style={styles.inputContainer}>
<Image
style={styles.inputIcon}
source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}
/>
<TextInput
style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid="transparent"
onChangeText={password => this.setState({password})}
/>
</View>
<TouchableHighlight
style={[styles.buttonContainer, styles.loginButton]}
onPress={() => this.onClickListener('login')}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => this.onClickListener('restore_password')}>
<Text>Forgot your password?</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => this.onClickListener('register')}>
<Text>Register</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#DCDCDC',
},
inputContainer: {
borderBottomColor: '#F5FCFF',
backgroundColor: '#FFFFFF',
borderRadius: 30,
borderBottomWidth: 1,
width: 250,
height: 45,
marginBottom: 20,
flexDirection: 'row',
alignItems: 'center',
},
inputs: {
height: 45,
marginLeft: 16,
borderBottomColor: '#FFFFFF',
flex: 1,
},
inputIcon: {
width: 30,
height: 30,
marginLeft: 15,
justifyContent: 'center',
},
buttonContainer: {
height: 45,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
width: 250,
borderRadius: 30,
},
loginButton: {
backgroundColor: '#00b5ec',
},
loginText: {
color: 'white',
},
});

Related

index.js:1 Unexpected text node: . A text node cannot be a child of a <View>

hellow, im new on react native, i want to create an app, fisrt in try to build its formula. it show me an error: {index.js:1 Unexpected text node: . A text node cannot be a child of a .}. here is my code i apreciate your help. (its a small calculator)
error: index.js:1 Unexpected text node: . A text node cannot be a child of a .
import React, {useState, useEffect, Component} from 'react';
import { AppRegistry, Text, View, TextInput, StyleSheet, Input, TouchableOpacity } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
export default class App extends Component {
constructor(props){
super(props);
this.state = {
numero1 : 0,
numero2 : 0,
resultado : 0
}
}
sumar = () => {
console.log(this.state.numero1);
let num1 = parseFloat(this.state.numero1);
let num2 = parseFloat(this.state.numero2);
let res = num1 + num2;
this.setState({resultado : res})
}
render(){
return (
<View style={styles.container}>
<View>
<Text style={styles.Titulos}>INVERGEGA</Text>
</View>
<View> <Text> VALOR 1 </Text> </View>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
value={this.state.numero1}
onChangeText={(text) => {this.setState({numero1 : text})}} />
</View>
<View> <Text>VALOR 2</Text> </View>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
value={this.state.numero2}
onChangeText={(text) => {this.setState({numero2 : text})}} />
</View>
<View>
<Text>RESULTADO</Text>
</View>
<View style={styles.container2}>
<Text name="resultado">{this.state.resultado}</Text>
</View>
<TouchableOpacity style={styles.container2} name="btnCalcular"
onPress={this.sumar}><Text> Hit me daddy!</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'gray',
},
inputContainer: {
width: '90%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 10,
borderWidth: 1,
borderColor: 'gray',
borderRadius: 30,
backgroundColor: 'lightgray'
},
textInput: {
paddingLeft: 10,
flex: 1,
height: 50,
},
container2: {
width: '90%',
height: '5%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 10,
borderWidth: 1,
borderColor: 'gray',
borderRadius: 30,
backgroundColor: 'white',
},
Text1: {
fontWeight: 'bold',
fontSize: 22,
color: 'red'
},
Text2: {
fontWeight: 'bold',
fontSize: 22,
},
Titulos: {
fontWeight: 'bold',
fontSize: 40,
}
}
);
AppRegistry.registerComponent('Bursakaxx1', () => App);

Make background dark grey when react native Modal is opened

I am using a react-native Modal, and I am trying to get the background to dim to a dark grey when it opens. I can't seem to get it to do this! I have tried adding a Main View and setting the backgroundColor of that to dark grey when the modal is opened, but it doesn't work. I have also tried setting the backgroundColor of the Modal to be dark grey when it opens - also doesn't work. How can I achieve this please? This is my code:
Link to Snack: https://snack.expo.dev/#steph510/simple-modal
App.js
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import Sortby from './components/Sortby';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
state = {
showSortby: false,
};
startSortByHandler = () => {
this.setState({
showSortby: true,
});
};
endSortByHandler = () => {
this.setState({
showSortby: false,
});
};
getSortValues = () => {
this.endSortByHandler()
}
getShowInGridViewList = () => {
const gridFieldArray = [
{"text":"Organization","key":"0.7204364607892255"},
{"text":"Document No","key":"0.11948720939854396"},
{"text":"Warehouse","key":"0.5981352662697218"},
{"text":"Business Partner","key":"0.3617080891091381"},
{"text":"Partner Address","key":"0.9242697027340077"},
{"text":"Movement Date","key":"0.19100558269330914"}]
return gridFieldArray;
};
render() {
return (
<View style={styles.container}>
<Card>
<Sortby
visible={this.state.showSortby}
onCancel={this.endSortByHandler}
showInGridViewList={this.getShowInGridViewList}
onOK={this.getSortValues}
></Sortby>
<Button title={'Open Modal'} onPress={this.startSortByHandler}></Button>
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#FFFFCC',
padding: 8,
}
});
SortBy.js
import React from "react";
import {View, Text, Modal, StyleSheet, Button, FlatList,} from "react-native";
import { RadioButton } from "react-native-paper";
export default class Sortby extends React.Component {
constructor(props) {
super(props);
}
state = {
selectedIndex: 0,
radioButtonValue: 'asc',
};
onRadiochange = (index, value) => {
this.setState({
radioButtonValue: value,
selectedIndex: index
});
};
render() {
return (
<Modal visible={this.props.visible} transparent={true}>
<View style={styles.modalStyles}>
<View style={styles.fieldsContainer}>
<FlatList
data={this.props.showInGridViewList()}
extraData={this.state}
renderItem={(itemData) => {
const index = itemData.index;
return (
<View style={styles.fieldItem}>
<Text style={styles.fieldText}>{itemData.item.text}</Text>
<View style={styles.radioButtonContainer}>
<RadioButton.Group onValueChange={value => this.onRadiochange(index, value)}>
<View style={styles.singleRadioButtonContainer}>
<Text>Asc</Text>
<RadioButton
color='#5d86d7'
value="asc"
status={ this.state.selectedIndex === index && this.state.radioButtonValue === 'asc' ? 'checked' : 'unchecked'}
/>
</View>
<View style={styles.singleRadioButtonContainer}>
<Text>Desc</Text>
<RadioButton
color='#5d86d7'
value="desc"
status={ this.state.selectedIndex === index && this.state.radioButtonValue === 'desc' ? 'checked' : 'unchecked'}
/>
</View>
</RadioButton.Group>
</View>
</View>
);
}}
alwaysBounceVertical={false}
/>
</View>
<View style={styles.buttonContainer}>
<View style={styles.button}>
<Button title="OK" color={"#5d86d7"} onPress={this.props.onOK}></Button>
</View>
<View style={styles.button}>
<Button
title="Cancel"
color={"#5d86d7"}
onPress={this.props.onCancel}
></Button>
</View>
</View>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
modalStyles: {
height: "auto",
width: "90%",
flexDirection: "column",
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#fff",
borderColor: "#777",
borderWidth: 1,
marginLeft: 20,
},
fieldsContainer: {
width: "100%",
},
fieldItem: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingLeft: 12,
borderBottomWidth: 1,
borderBottomColor: "#ebebeb",
},
fieldText: {
color: "#444",
},
radioButtonContainer: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
},
singleRadioButtonContainer: {
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
marginRight: 10,
},
buttonContainer: {
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
button: {
width: "100%",
marginHorizontal: 8,
},
});
Here is a solution I found: https://snack.expo.dev/C1gQM9bvD
I assume that the Modal from react-native does not support this directly since in their docs they do not mention anything like this.
However, you can check this library, I used it multiple times and you can customize it.
I have created a container style then I applied the rgba values for backgroundColor e.g:
modalStyles:{
flex: 1,
//backgroundColor: 'transparent',
backgroundColor: 'rgba(0,0,0,0.7)',
alignItems: 'center',
justifyContent: 'center',
},
Then inside the modal I created my actual modal dialog inside it.
Did you try the customBackdrop prop?
<Modal
visible={this.props.visible}
statusBarTranslucent={true}
customBackdrop={<View style={{backgroundColor: '#FFFFCC'} />}
>

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working. Can any one help me?

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working.
See the Screenshot Here
Currently, when changing the price by touch input, the price is not affected when click off.
Here are my files
CartItem.js:
import React from "react";
import {
View,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
Platform,
Alert,
} from "react-native";
//Colors
import Colors from "../../../utils/Colors";
//NumberFormat
import NumberFormat from "../../../components/UI/NumberFormat";
//Icon
import { MaterialCommunityIcons } from "#expo/vector-icons";
import CustomText from "../../../components/UI/CustomText";
//PropTypes check
import PropTypes from "prop-types";
export class CartItem extends React.PureComponent {
render() {
const { item, onAdd, onDes, onRemove } = this.props;
const AddItemHandler = async () => {
await onAdd();
};
const sum = +item.item.price * +item.quantity;
const checkDesQuantity = async () => {
if (item.quantity == 1) {
Alert.alert(
"Clear cart",
"Are you sure you want to remove the product from the cart?",
[
{
text: "Cancel",
},
{
text: "Yes",
onPress: onRemove,
},
]
);
} else {
await onDes();
}
};
return (
<View style={styles.container}>
<View style={styles.left}>
<Image
style={{
width: "100%",
height: 90,
resizeMode: "stretch",
borderRadius: 5,
}}
source={{ uri: item.item.thumb }}
/>
</View>
<View style={styles.right}>
<View
style={{ flexDirection: "row", justifyContent: "space-between" }}
>
<CustomText style={styles.title}>{item.item.filename}</CustomText>
<View>
<TouchableOpacity onPress={onRemove}>
<MaterialCommunityIcons name='close' size={20} color='#000' />
</TouchableOpacity>
</View>
</View>
<CustomText style={{ color: Colors.grey, fontSize: 12 }}>
Provided by Brinique Livestock LTD
</CustomText>
<NumberFormat price={sum.toString()} />
<View style={styles.box}>
<TouchableOpacity onPress={checkDesQuantity} style={styles.boxMin}>
<MaterialCommunityIcons name='minus' size={16} />
</TouchableOpacity>
Code that I would like to be fixed starts here.
<View>
<TextInput
keyboardType='numeric'
onEndEditing={AddItemHandler}
style={styles.boxText}>{item.quantity}</TextInput>
</View>
Code that I would like to be fixed ends here.
<TouchableOpacity
onPress={AddItemHandler}
style={styles.boxMin}>
<MaterialCommunityIcons name='plus' size={16} />
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
CartItem.propTypes = {
item: PropTypes.object.isRequired,
onAdd: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onDes: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginHorizontal: 10,
height: 110,
borderBottomWidth: 1,
borderBottomColor: Colors.light_grey,
flexDirection: "row",
paddingVertical: 10,
alignItems: "center",
backgroundColor: "#fff",
paddingHorizontal: 10,
borderRadius: 5,
marginTop: 5,
},
left: {
width: "35%",
height: "100%",
alignItems: "center",
},
right: {
width: "65%",
paddingLeft: 15,
height: 90,
// overflow: "hidden",
},
title: {
fontSize: 14,
},
box: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: Platform.OS === "ios" ? 30 : 25,
backgroundColor: Colors.grey,
width: 130,
borderRadius: 5,
paddingHorizontal: 15,
marginTop: 5,
},
boxMin: {
width: "30%",
alignItems: "center",
},
boxText: {
fontSize: 16,
backgroundColor: Colors.white,
padding: 5,
},
});
Use onBlur instead of onEndEditing.
How should the input end triggered?
After a time?
When user hits enter?
When user taps anywhere to close software keyboard?
Instead of
onEndEditing={AddItemHandler}
Use:
onBlur={(e) => {AddItemHandler(e.nativeEvent.text)}}
And ensure that AddItemHandler can handle the value in e.nativeEvent.text.

How to implement time picker functionality in react native

I want to implement a functionality that should allow me to pick time within a range.
it should be like this
I have used react-native-slider and my code is here
import React, { Component } from 'react';
import { View, Text, Image, TextInput, StyleSheet } from 'react-native';
import Slider from 'react-native-slider';
import colors from '../styles/colors';
import Strings from '../localization/strings';
class FindDoctor extends Component {
constructor(props) {
super(props);
this.state = {
value: 6,
};
}
getInitialState() {
return {
value: 2,
};
}
render() {
return (
<View style={styles.container}>
<View style={{ flexDirection: 'column', margin: 20 }}>
<Text style={styles.textStyle}>Looking for</Text>
<View style={styles.input}>
<TextInput
placeholder={Strings.InternalMedicine}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor={colors.dimgray}
underlineColorAndroid="transparent"
onChangeText={TextInputName => this.setState({ TextInputName })}
/>
</View>
</View>
<View style={{ flexDirection: 'column', margin: 20 }}>
<Text style={styles.textStyle}>Near</Text>
<View style={styles.input}>
<TextInput
placeholder={Strings.Place}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor={colors.dimgray}
underlineColorAndroid="transparent"
onChangeText={TextInputName => this.setState({ TextInputName })}
/>
</View>
</View>
<View style={{ flexDirection: 'column', margin: 20 }}>
<Text style={styles.textStyle}>Within</Text>
<View style={styles.sliderStyles}>
<Slider
value={this.state.value}
onValueChange={(value) => this.setState({ value })}
minimumValue={4}
maximumValue={10}
step={10}
/>
<Text>value: {this.state.value}</Text>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
textStyle: {
fontSize: 20,
color: colors.brandBlue,
},
input: {
backgroundColor: colors.white,
height: 40,
width: '80%',
marginTop: 5,
borderRadius: 4,
alignItems: 'flex-start',
justifyContent: 'flex-start',
borderWidth: 1,
borderColor: colors.light_gray,
fontSize: 20
},
sliderStyles: {
//margin: 10,
alignItems: 'stretch',
justifyContent: 'center',
},
});
export default FindDoctor;
and now the output look like this
But i want to add multiples values in slider like the image shown above
can anyone help me to add multiple values in slider

How to get total view to center in react native

I am new to react native, and I have created one sample login form. In this form i want to align total view to center. I tried this way but not working, Can You guide me how to achieve this.
My login class is
import React, {Component} from 'react';
import {AppRegistry,Text, View,TextInput,TouchableOpacity,StyleSheet} from 'react-native';
export default class Login extends Component{
render(){
return(
<View style={styles.container}>
<TextInput style={styles.textInput} placeholder="Acc No/User ID"/>
<TextInput style={styles.textInput} placeholder="Password"/>
<TouchableOpacity style={styles.btn} onPress={this.login}><Text>Log In</Text></TouchableOpacity>
</View>
);
}
login=()=>{
alert("testing......");
// this.props.navigation.navigate('Second');
}
}
AppRegistry.registerComponent('Login', () => Login);
const styles = StyleSheet.create({
container:{
justifyContent: 'center',
alignItems: 'center',
},
header: {
fontSize: 24,
marginBottom: 60,
color: '#fff',
fontWeight: 'bold',
},
textInput: {
alignSelf: 'stretch',
padding: 10,
marginLeft: 80,
marginRight:80,
},
btn:{
alignSelf: 'stretch',
backgroundColor: '#01c853',
padding: 10,
marginLeft: 80,
marginRight:80,
alignItems: 'center',
}
});
And the following is the screen shot of above code.
And i tried with the bellow code, but not working
container:{
justifyContent: 'center',
alignItems: 'center',
flex:1
},
So please help me, how to do this?
Thanks In Advance..
Use the flex display : https://css-tricks.com/snippets/css/a-guide-to-flexbox/
import React, { Component } from 'react';
import { AppRegistry, Text, View, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
export default class Login extends Component {
render() {
return (
<View style={styles.container}>
<TextInput style={styles.textInput} placeholder="Acc No/User ID" />
<TextInput style={styles.textInput} placeholder="Password" />
<TouchableOpacity style={styles.btn} onPress={this.login}><Text>Log In</Text></TouchableOpacity>
</View>
);
}
login = () => {
alert("testing......");
// this.props.navigation.navigate('Second');
}
}
AppRegistry.registerComponent('Login', () => Login);
const styles = StyleSheet.create({
container: {
display: 'flex',
flexDirection: 'column',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
header: {
fontSize: 24,
color: '#fff',
fontWeight: 'bold',
},
textInput: {
padding: 10,
textAlign: 'center',
},
btn: {
backgroundColor: '#01c853',
paddingVertical: 10,
paddingHorizontal: 50,
}
});
And by the way, you could have easily found an answer with a simple search (Vertically center view react-native) : https://moduscreate.com/blog/aligning-children-using-flexbox-in-react-native/
just add flex :1 to your container style
container:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
}
import React,{Component} from 'react';
import {View,Text,TextInput, Button,StyleSheet,Alert} from 'react-native';
class App extends Component{
state = {
userId:'',
password:'',
};
render(){
return(
<View style={styles.container}>
<View>
</View>
<View>
<TextInput
placeholder="User ID"
style={styles.loginTextInput}
onChangeText={(value) => this.setState({userId: value})}
value={this.state.userId}
></TextInput>
<TextInput
placeholder="Password"
style={styles.loginTextInput}
onChangeText={(value)=>this.setState({password:value})}
></TextInput>
<Button
title="Login"
style={styles.loginBtn}
onPress={this.loginCheck}
></Button>
</View>
</View>
)
}
loginCheck=()=>{
if((this.state.userId=='admin') && (this.state.password=='admin')){
Alert.alert("Login Success");
}else{
Alert.alert("User and password is not match\n Please try again");
}
}
}
export default App;
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
},
loginTextInput:{
borderColor:'#ebe9e6',
borderWidth:1,
margin:5,
},
loginBtn:{
backgroundColor: '#01c853',
paddingVertical: 10,
paddingHorizontal: 50,
}
})