how to get TextInput value without using state in react native android - android

Here i am trying to get the TextInput value using the const value username and password but i get undefined. How to use state or props in this. I followed this tutorial https://medium.com/react-native-training/react-native-navigator-experimental-part-2-implementing-redux-c6acbf66eca1#.d0vteepp7
import React, { Component } from 'react'
import {
View,
Text,
TextInput,
Alert
} from 'react-native'
import Button from './Button'
const route = {
type: 'push',
route: {
key: 'about',
title: 'About'
}
}
const _values = {
username: '',
password: ''
}
const LoginView = ({_handleNavigate}) => {
const _handlePress = () => {
const {username, password} = _values
console.log('username' + username + "" + password);
return fetch('http://webservice.net/User/ValidateUser', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
UserName: username,
Password: password,
DeviceType: 'Android',
DeviceToken: 'eU0z3IR96Mg:APA91bHNyEw3CcMCHZ-MmGhFVRV8XT292NYzrD2xedMFLXdaJqcJ4DXlBmn'
})
}).then(response => response.json())
.then(response => {
console.log(response);
Alert.alert('Response message is:', response.parse)
_handleNavigate(route)
return response;
})
.catch(error => {
console.error(error);
});
};
return (
<View style={{ flex: 1, backgroundColor: 'steelblue', padding: 10, justifyContent: 'center' }}>
<Text style={{ backgroundColor: 'steelblue', justifyContent: 'center', alignItems: 'center', fontSize: 40, textAlign: 'center', color: 'white', marginBottom: 30 }}>
LOGIN
</Text>
<View style={{ justifyContent: 'center' }}>
<TextInput
style={{ height: 40, margin: 30, color: 'white', fontSize: 20 }}
placeholder='Username' placeholderTextColor='white'
autoFocus={true}
/>
<TextInput
secureTextEntry={true}
style={{ height: 40, margin: 30, color: 'white', fontSize: 20 }}
placeholder='Password' placeholderTextColor='white'
/>
</View>
<Button onPress={() => { _handlePress() } } label='Login' />
</View>
)
}
export default LoginView

You can attach TextInput's onChangeText event' handler and store its argument , like:
<TextInput
onChangeText={(val) => _values.username = val}
...
/>

Related

ERROR TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined)

store.js
// Imports: Dependencies
import { createStore } from 'redux';
import employeeDetailReducer from './employeeDetailReducer';
// Middleware: Redux Persist Config
const store = createStore(employeeDetailReducer);
employeeDetailReducer.js
const initialState = {
employeeDetails: {
name: "",
schoolName: "",
companyName: ""
}
};
const employeeDetailReducer = (state = initialState, action) => {
switch (action.type) {
case "SAVE_EMPLOYEE_DETAIL": {
return {
...state,
employeeDetails: action.employeeDetails
}
}
default: {
return state;
}
}
}
export default employeeDetailReducer;
EmployeeDetails.js
import React from "react";
import { View, Text, StyleSheet, SafeAreaView, TextInput, TouchableHighlight } from "react-native";
import { connect } from "react-redux"
import { saveEmployeeDetails } from "./saveEmployeeDetailAction"
class EmployeeDetails extends React.Component {
constructor(props) {
super(props)
this.state = {
name: "",
schoolName: "",
companyName: ""
}
}
render() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.mainView}>
<Text style={styles.mainTextStyle}>Submit Employee Details</Text>
<Text style={styles.textStyle}>Enter Your Name</Text>
<TextInput
style={styles.textInputStyle}
underlineColorAndroid="transparent"
placeholderTextColor="#cccccc"
placeholder="Enter Your Name"
onChangeText={name => {
this.setState({ name: name }, () => {
});
}}
/>
<Text style={styles.textStyle}>Enter Your School Name</Text>
<TextInput
style={styles.textInputStyle}
underlineColorAndroid="transparent"
placeholderTextColor="#cccccc"
placeholder="Enter Your School Name"
onChangeText={schoolName => {
this.setState({ schoolName: schoolName }, () => {
});
}}
/>
<Text style={styles.textStyle}>Enter Your Company Name</Text>
<TextInput
style={styles.textInputStyle}
underlineColorAndroid="transparent"
placeholderTextColor="#cccccc"
placeholder="Enter Your Company Name"
onChangeText={companyName => {
this.setState({ companyName: companyName }, () => {
});
}}
/>
<TouchableHighlight
underlayColor="transparent"
style={styles.buttonStyle}
onPress={() => {
var employeeDetails = {};
employeeDetails.name = this.state.name;
employeeDetails.schoolName = this.state.schoolName;
employeeDetails.companyName = this.state.companyName;
this.props.reduxSaveEmployeeDetail(employeeDetails)
this.props.navigation.navigate("ShowEmployeeDetail")
}}
>
<Text style={styles.buttonTextStyle}>Submit</Text>
</TouchableHighlight>
</View>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: "100%",
height: "100%",
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: "lightgray",
paddingBottom: 50
},
mainView: {
width: "100%",
height: "50%",
justifyContent: "flex-start",
alignItems: "center",
padding: 20,
},
textInputStyle: {
width: "100%",
height: 40,
backgroundColor: "white",
paddingHorizontal: 15,
marginBottom: 10,
marginTop: 10
},
textStyle: {
width: "100%",
height: 20,
textAlign: "left",
marginTop: 10,
fontSize: 15
},
mainTextStyle: {
width: "100%",
height: 40,
//paddingHorizontal:15,
textAlign: "center",
marginTop: 10,
marginBottom: 10,
fontSize: 20
},
buttonStyle: {
width: "100%",
height: 40,
borderRadius: 5,
justifyContent: "center",
alignItems: "center",
backgroundColor: "white",
marginTop: 20
},
buttonTextStyle: {
width: "100%",
height: "100%",
textAlign: "center",
marginTop: 10,
fontSize: 18
},
})
const mapDispatchToProps = (dispatch) => {
return {
reduxSaveEmployeeDetail: (employeDetails) => dispatch(saveEmployeeDetails(employeDetails))
}
}
export default connect(
null,
mapDispatchToProps
)(EmployeeDetails);
App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store'
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import EmployeeDetali from './EmployeeDetali';
import ShowEmployeeDetail from './ShowEmployeeDetail';
export default App = () => {
return (
<Provider store={store}>
<AppNavigator />
</Provider>
);
};
const Stack = createNativeStackNavigator();
const AppNavigator = () => {
return (
<NavigationContainer initialState="EmployeeDetali">
<Stack.Screen name="EmployeeDetali" component={EmployeeDetali} />
<Stack.Screen name="ShowEmployeeDetail" component={ShowEmployeeDetail} />
</NavigationContainer>
)
}
Error
ERROR TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined)
This error is located at:
in Provider (created by App)
in App
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in ReactNativeApp(RootComponent)
I don't know what is wrong here...
I'm also add store like this
import {store} from './store'
It also give me error so how can soul my error where is my error
I don't have any idea for adding redux in class component so how I can do this
I'm learning from here
I also learn redux
so anyone give me suggestion what happing in my code
Do,
export { store };
in store.js.
and,
import {store } from "./store";
in app.js

How do you change the entire selection to individual choices in React Native?

We are currently developing based on React Native.
And I received data by GET request through API document,
and I created scroll view through MAP method.
So now I'm trying to make it possible to choose,
but if I choose one, it's all chosen.
How can I make you choose one by one if I choose one from my code?
import React, { useEffect, useState } from "react";
import { SvgCssUri } from "react-native-svg";
import { DeviceEventEmitter } from "react-native";
import {
View,
StyleSheet,
TouchableHighlight,
Text,
ScrollView,
Image,
} from "react-native";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import axios from "axios";
import BouncyCheckbox from "react-native-bouncy-checkbox";
const Select = ({ navigation }) => {
let bouncyCheckboxRef = null;
const [bodyType, setBodyType] = useState([]);
const [standardSelected, setStandardSelected] = useState(false);
const [isSelected, setSelected] = useState(false);
const bodyGetData = async () => {
let body = [];
try {
let config = {
method: "get",
url:
"http://everyweardev-env.eba-azpdvh2m.ap-northeast-2.elasticbeanstalk.com/api/v1/user/bodyType/male",
headers: {},
};
axios(config).then(function (response) {
response.data.data.map((u) => {
switch (u.bodyType) {
case "standard":
body.push({ bodyType: "스탠다드", imgUrl: u.imgUrl, key: 1 });
break;
case "reverseTriangle":
body.push({ bodyType: "역삼각형", imgUrl: u.imgUrl, key: 2 });
break;
case "triangle":
body.push({ bodyType: "삼각형", imgUrl: u.imgUrl, key: 3 });
break;
case "circle":
body.push({ bodyType: "원형", imgUrl: u.imgUrl, key: 4 });
break;
case "hourglass":
body.push({ bodyType: "직사각형", imgUrl: u.imgUrl, key: 5 });
break;
}
});
return setBodyType(body);
});
} catch (err) {
console.log(err);
}
};
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
bodyGetData();
});
return unsubscribe;
}, [navigation]);
const onClick = (e) => {
console.log(e);
bodyType.map((u) => {
switch (u.bodyType) {
case u.bodyType === "스탠다드":
setSelected(!isSelected);
console.log(isSelected);
break;
case "역삼각형":
setSelected(!isSelected);
break;
}
});
};
return (
<View style={styles.container}>
<Text
style={{ fontSize: wp("5.5%"), fontWeight: "bold", marginBottom: 21 }}
>
자신의 체형을 선택해 주세요
</Text>
<View style={{ flexDirection: "row", marginBottom: hp("10%") }}>
<Text style={{ fontSize: wp("4.5%"), marginRight: wp("1%") }}>
더 정확한 평가를 받으실 수 있습니다
</Text>
<Image
source={require("../../images/smile.png")}
style={{ marginTop: hp("0.5%") }}
/>
</View>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={true}>
{bodyType.map((data) => (
<>
<TouchableHighlight
style={styles.bodySelect}
value={data.bodyType}
onPress={onClick}
// onPress={() => bouncyCheckboxRef?.onPress()}
>
<>
<BouncyCheckbox
isChecked={!isSelected}
ref={(ref) => (bouncyCheckboxRef = ref)}
size={25}
fillColor="black"
unfillColor="#FFFFFF"
iconStyle={{ borderColor: "white" }}
textStyle={{ fontFamily: "JosefinSans-Regular" }}
disableBuiltInState
onPress={onClick}
style={{
alignSelf: "flex-start",
marginLeft: wp("3%"),
marginTop: hp("2%"),
}}
/>
<SvgCssUri
uri={data.imgUrl}
width="90%"
height="60%"
marginTop="-5%"
key={data.key}
/>
<Text style={styles.bodytype}>{data.bodyType}</Text>
</>
</TouchableHighlight>
</>
))}
</ScrollView>
<TouchableHighlight
style={styles.button}
onPress={() => {
navigation.navigate("얼굴형 정보 입력");
}}
underlayColor="gray"
>
<>
<Text style={styles.text}>선택 완료</Text>
</>
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: "center",
alignItems: "center",
marginTop: hp("5%"),
},
button: {
justifyContent: "center",
alignItems: "center",
width: wp("70%"),
height: hp("7%"),
color: "white",
backgroundColor: "black",
borderRadius: 10,
marginTop: hp("17%"),
},
text: {
color: "white",
fontSize: wp("5.2%"),
fontWeight: "bold",
},
bodySelect: {
marginLeft: 16,
marginRight: 16,
width: wp("70%"),
height: hp("35%"),
alignItems: "center",
borderRadius: 30,
backgroundColor: "#ffffff",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
bodytype: {
marginTop: hp("3%"),
fontWeight: "bold",
fontSize: wp("8%"),
},
});
export default Select;
this example explain how to select individual choice.
do these steps :
//define state to save selected value inside it
const [selected, setSelected] = React.useState();
//handle item onPress
const onPress = (item) => {
setSelected(item);
}
//check if item selected
const isSelected = (item) => {
return selected?.unique_id === item.unique_id;
}
//and in render function
<ScrollView>
{
data.map((item, index) => {
return(
<ItemComponent
onPress={() => setSelected(item)}
style={isSelected(item) ? selectedStyle : defaultStyle}>
</ItemComponent>
)
})
}
</ScrollView>
full code try snack here
import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, TouchableOpacity} from 'react-native';
export default function App() {
const [selected, setSelected] = React.useState();
const data = [
{
unique_id : 1,
text : "item one"
},
{
unique_id : 2,
text : "item two"
},
{
unique_id : 3,
text : "item three"
},
{
unique_id : 4,
text : "item four"
}
];
const onPress = (item) => {
setSelected(item);
}
const isSelected = (item) => {
return selected?.unique_id === item.unique_id;
}
return (
<ScrollView>
{
data.map((item, index) => {
return(
<TouchableOpacity
key={item.unique_id}
onPress={() => {
setSelected(item);
}}
style={{
padding : 25,
margin : 10,
backgroundColor : isSelected(item) ? "red" : "#eee"
}}
>
<Text>{item.text}</Text>
</TouchableOpacity>
)
})
}
</ScrollView>
);
}

I can try create login page but getting error on state email

import React, { Component } from 'react';
import {
SafeAreaView,
Text,
View,
Image,
ScrollView,
StyleSheet,
StatusBar,
TextInput,
TouchableOpacity
} from 'react-native';
export default class LoginFrom extends React. Component {
state = {
isLoading: false,
strEmail: "test#example.com", isEmailValid: true, errMsgEmail: "",
strPassword: "test#123", isPasswordValid: true, errMsgPassword: "",
strErrMsg: ""
}
login() {
setTimeout(() => {
fetch("url", {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
'email': this.state.strEmail,
'password': this.state.strPassword
})
}).then((response) => {
if (response.status == 200) {
return response.json()
} else {
return null
}
}).then((responseJson) => {
console.log(responseJson);
if (responseJson != null) {
this.setState({
strErrMsg: ""
})
} else {
this.setState({
strErrMsg: "Email and password does not match."
})
}
})
}, 100);
}
txtEmailChangeHangler = (val) => {
this.setState({
strEmail: val.trim()
})
}
txtPasswordChangeHangler = (val) => {
this.setState({
strPassword: val.trim()
})
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.inputbox}
onSubmitEditing={() => { this.secondTextInput.focus(); }}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='Email'
selectionColor='#fff'
value={this.state.strEmail}
onChangeText={this.txtEmailChangeHangler}
keyboardType='email-address' />
<TextInput
secureTextEntry={true}
style={styles.inputbox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='password'
onChangeText={this.txtPasswordChangeHangler}
value={this.state.strPassword}
ref={(input) => { this.secondTextInput = input; }} />
<TouchableOpacity onPress={this.login} style={styles.button}>
<Text style={styles.buttontext}>{this.props.type}</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#D3EDFA',
flexGrow: 1,
alignItems: 'center',
justifyContent: 'center'
},
inputbox: {
width: 300,
backgroundColor: 'rgba(255,255,255,1)',
borderRadius: 25,
paddingHorizontal: 16,
marginVertical: 10
},
button: {
width: 300,
backgroundColor: '#ED6825',
borderRadius: 25,
paddingVertical: 16,
marginVertical: 10
},
buttontext:
{
fontSize: 16,
color: '#ffffff',
fontWeight: '100',
textAlign: 'center',
paddingHorizontal: 16,
}
})
Just try replacing login function with fat arrow function
login() {
// your code here
}
to
login = () => {
// your code here
}
hope it helps, this is done because fat arrow functions implicty binds this keyword

React Native: Blank space between FlatList rendered items

I'm trying to display some fetched data in app using FlatList . It works but there is a bloody big space between items!
Here is my FlatList code:
<View style={styles.showresp}>
<FlatList
data={this.state.responsjson}
renderItem={({ item }) =>
<View style={styles.weatherview}>
<Text style={styles.city}>{item.name}</Text>
<Text style={styles.country}>{item.country}</Text>
<Text style={styles.temp}>{item.temp_c}</Text>
</View>}/>
</View>
this is what i see in screen
and it is styles :
showresp: {
backgroundColor: '#fffa',
height: 315,
marginRight: '10%',
marginLeft: '10%',
marginTop: '15%',
borderRadius: 15
},
weatherview:{
alignItems: 'center',
justifyContent: 'center',
flex :1
},
city: {
fontFamily :'Wonderbar Demo',
fontSize:40,
color:'#880e4f',
},
country:{
fontSize:20,
fontFamily:'Samim-Bold',
backgroundColor:'red',
},
temp:{
fontFamily :'Wonderbar Demo',
fontSize : 40,
backgroundColor:'green',
},
I set the background color for up and down Texts to find the problem but i don't have any bloody idea about it.
could you guide me on this matter?ಠ_ಠ
I made an example for you. Look at this. The difference between you and me is no margin.
And I have my parents as a flatist.
You don't have to put View aside like this. You can put the view in the item you want.
import React, { Component } from 'react';
import { View, Text, FlatList } from 'react-native';
const users = [
{
name: 'Cathy Gilliam',
company: 'EXOVENT',
email: 'cathygilliam#exovent.com',
},
{
name: 'Norton Potts',
company: 'COREPAN',
email: 'nortonpotts#corepan.com',
},
{
name: 'Kelly Collins',
company: 'SECURIA',
email: 'kellycollins#securia.com',
},
];
export default class App extends Component {
render() {
return (
<FlatList
data={users}
renderItem={({ item }) => (
<View
style={{
borderBottomWidth: 1,
borderBottomColor: 'grey',
padding: 10
}}>
<View>
<Text style={{ fontWeight: 'bold', fontSize: 18 }}>{item.name}</Text>
<Text>{item.company}</Text>
<Text>{item.email}</Text>
</View>
</View>
)}
/>
);
}
}
It should work:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
responsjson: [{
name: 'Name1',
country: 'Country1',
temp_c: '45'
},
{
name: 'Name2',
country: 'Country2',
temp_c: '45'
}]
};
}
render() {
return (
<View style={styles.showresp}>
<FlatList
data={this.state.responsjson}
renderItem={({ item }) =>
<View style={styles.weatherview}>
<Text style={styles.city}>{item.name}</Text>
<Text style={styles.country}>{item.country}</Text>
<Text style={styles.temp}>{item.temp_c}</Text>
</View>} />
</View>
);
}
}
const styles = StyleSheet.create({
showresp: {
backgroundColor: '#fffa',
height: 315,
marginRight: '10%',
marginLeft: '10%',
marginTop: '15%',
borderRadius: 15
},
weatherview: {
alignItems: 'center',
justifyContent: 'center',
flex: 1
},
city: {
fontFamily: 'Wonderbar Demo',
fontSize: 40,
color: '#880e4f',
},
country: {
fontSize: 20,
fontFamily: 'Samim-Bold',
backgroundColor: 'red',
},
temp: {
fontFamily: 'Wonderbar Demo',
fontSize: 40,
backgroundColor: 'green',
},
});
Image:

Request Keys of value that is not an object in React native listview while fetching json from api?

This may be dumb question but as a beginner am struggling with this don't know where am making mistake when am trying to fetch jsonarray value from api am getting Requested keys of a value that is not an object don't know where am making mistake now let me post what i have tried so far
this is the index.android code
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
ListView,
Image,
View
} from 'react-native';
var REQUEST_URL = 'http://someurl';
var AwesomeProject = React.createClass({
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
},
render: function() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
},
renderLoadingView: function() {
return (
<View style={styles.container}>
<Text>
Loading movies...
</Text>
</View>
);
},
renderMovie: function(movie) {
return (
<View style={styles.container}>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.HeaderText}</Text>
<Text style={styles.year}>{movie.SubText}</Text>
</View>
</View>
);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
This is the response am getting from api :
[{"HeaderText":"Contract Approval","ApprovalType":"C","ApprovalCount":0,"SubText":"New / Change","ApproverID":198},{"HeaderText":"Contract Specification Approval","ApprovalType":"CS","ApprovalCount":0,"SubText":"New / Change","ApproverID":198},{"HeaderText":"Spare Part Request Approval","ApprovalType":"SPR","ApprovalCount":0,"SubText":"New / Change","ApproverID":198},{"HeaderText":"Spare Part Non Return Approval","ApprovalType":"SPNR","ApprovalCount":0,"SubText":"New / Change","ApproverID":198},{"HeaderText":"Spare Purchase Request Approval","ApprovalType":"SPRA","ApprovalCount":0,"SubText":"New / Change","ApproverID":198},{"HeaderText":"Spare Request Approval","ApprovalType":"SSRA","ApprovalCount":0,"SubText":"New / Change","ApproverID":198}]
Getting requested keys of a value that is not an object can anyone help me am struggling with this. Thanks in advance!!

Categories

Resources