could you please tell me how to get input field value or in other words username and password input field value on button click .
here is my code
https://rnplay.org/apps/drT9vw
import React from 'react';
import {
registerComponent,
} from 'react-native-playground';
import {
Text,
View,
Image,
StyleSheet,
TextInput,
TouchableHighlight
} from 'react-native';
class App extends React.Component {
constructor(props){
super(props);
this.state ={
userName :'',
password:''
};
}
login(){
alert(this.state.userName)
}
OnChangesValue(e){
console.log(e.nativeEvent.text);
this.setState({
userName :e.nativeEvent.text,
})
}
changePassword(e){
console.log(e.nativeEvent.text);
this.setState({
password :e.nativeEvent.text,
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.heading}> Login</Text>
<TextInput
style={styles.loginInput}
onChange={(text)=> this.setState({userName:text})}
ref="myInput"
underlineColorAndroid='transparent'
placeholder="username !"
/>
<TextInput
style={styles.loginInput}
ref="pass"
onChange={this.changePassword.bind(this)}
underlineColorAndroid='transparent'
placeholder="password to ff!"
secureTextEntry={true}
/>
<TouchableHighlight style={styles.touchable} onPress={this.login.bind(this)}>
<Text style={styles.touchableButton}>Click</Text>
</TouchableHighlight>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#EF501E',
flex: 1,
alignItems: 'center',
padding :20
},
logo: {
width: 50,
height: 50
},
heading: {
fontSize: 30,
marginTop: 20
},
loginInput: {
height: 50,
alignSelf: 'stretch',
borderWidth: 1,
borderColor: '#33090C',
flexDirection: 'row',
justifyContent: 'center',
marginBottom:10
},
touchable:{
backgroundColor:'#2E18DD',
height:40,
alignSelf:'stretch',
alignItems:'center',
justifyContent:'center'
},
touchableButton:{
color:'#fff',
fontSize:10
}
});
registerComponent(App);
update
login(){
alert(this.refs.myInput.value)
}
it give undefined
Not getting the exact issue, u are storing the userName and password in state variable. So you can get the values the by this.state.userName and this.state.password. or u can use the refs also to get the value like this: this.refs.myInput.value.
Change this fun:
changePassword(text){
console.log(text);
this.setState({
password :text,
})
}
Check the same example on tutorialspoint: https://www.tutorialspoint.com/react_native/react_native_text_input.htm
It can be done in two ways. If the input fields are controlled, you can get the values from the state itself. In case of uncontrolled input fields (your case), you can use refs to get the input values
login() {
console.log(this.refs.myInput.value)
}
Related
I am creating an Application using React Native and Node.js at the backend. I am using Axios to call the API services. The API will show a response if a user is created successfully. Fortunately it shows. However if an user already exists, then it is still supposed to return a message by saying "User already exists". This however works with postman but unfortunately when I try from my react native front-end, I am getting an Error 400. Basically, I want to show my user that particular message where the API returns that user already exists. Here is my code:
import React, { Component } from "react";
import { render } from "react-dom";
import { ImageBackground, SafeAreaView, StyleSheet, View, Image, Text, Button, TouchableWithoutFeedback, TouchableOpacity, TextInput } from "react-native";
import axios from "axios";
class Welcome extends Component {
constructor() {
super();
this.state = {
username : "",
email : "",
password: "",
}
}
submit = () => {
console.log(this.state.email);
console.log(this.state.username);
console.log(this.state.password);
//Here comes the magic
axios
.post(`http://localhost:8080/api/auth/signup`, {
username: this.state.username,
email: this.state.email,
password: this.state.password,
})
.then((response) => {
console.log(response.data);
});
}
render() {
const test = () => {
console.log("Test Completed");
}
const buttonFeedback = (data) => {
if(data === 1) {
console.log("Login Button Detected!");
}
if(data === 2) {
console.log("Registration Button Detected!");
}
}
return (
<>
<ImageBackground style={styles.background}
source={require("../assets/background.png")}>
<View style={styles.logoContainer}>
<Image style={styles.logo} source={require("../assets/icon.png")}/>
<Text>Welcome to our application</Text>
<br></br>
<TextInput
placeholder="Your Email"
onChangeText={(text)=> {this.setState({ email: text})}}
/><br></br>
<TextInput
placeholder="Your Username"
onChangeText={(text)=> {this.setState({ username: text})}}
/><br></br>
<TextInput
placeholder="Your Password"
onChangeText={(text)=> {this.setState({ password: text})}}
/><br></br>
<Button title="Register" onPress={()=> this.submit()}/>
</View>
<TouchableOpacity style={styles.loginButton} onPress={()=> buttonFeedback(1)}>
<View><Text style={styles.text}>Log In</Text></View>
</TouchableOpacity>
<TouchableOpacity style={styles.registerButton} onPress={()=> buttonFeedback(2)}>
<View><Text style={styles.text}>Register</Text></View>
</TouchableOpacity>
</ImageBackground>
</>
);
}
}
export default Welcome;
const styles = StyleSheet.create({
background: {
flex: 1,
justifyContent: "flex-end",
alignItems: "center"
},
loginButton: {
width: '100%',
height: 70,
backgroundColor: '#fc5c65',
alignItems: 'center'
},
registerButton: {
width: '100%',
height: 70,
backgroundColor: '#4ecdc4',
alignItems: 'center'
},
logo: {
width: 100,
height: 100,
},
logoContainer: {
position: "absolute",
top: 70,
alignItems: "center"
},
text: {
color: 'white',
}
})
Can anyone tell me how to resolve this?
I have generated QR Code manually by asking user to input value but what I'm trying is to generate QR Code random(Qr should be generated from number) without asking input from user so how can I generate random QR Code by pressing button only? I'm working on project that requires random QR Code every time when they open their mobile app.
Here is my code:
import React, { Component } from "react";
import {
StyleSheet,
View,
TextInput,
TouchableOpacity,
Text,
} from "react-native";
import QRCode from "react-native-qrcode-svg";
class QrGenerator extends Component {
constructor() {
super();
this.state = {
// Default Value of the TextInput
inputValue: "",
// Default value for the QR Code
valueForQRCode: "",
};
}
getTextInputValue = () => {
this.setState({
valueForQRCode: this.state.inputValue,
});
};
render() {
return (
<View style={styles.MainContainer}>
<QRCode
//Setting the value of QRCode
value={"ComputerGen" + this.state.valueForQRCode}
//Size of QRCode
size={250}
//Background Color of QRCode
bgColor="#000"
//Front Color of QRCode
fgColor="#fff"
getRef={(ref) => (this.svg = ref)}
onPress={() => {}}
/>
<TextInput // Input to get the value to set on QRCode
style={styles.TextInputStyle}
onChangeText={(text) => this.setState({ inputValue: text })}
underlineColorAndroid="transparent"
placeholder="Enter text to Generate QR Code"
/>
<TouchableOpacity
onPress={this.getTextInputValue}
activeOpacity={0.7}
style={styles.button}
>
<Text style={styles.TextStyle}> Generate QR Code </Text>
</TouchableOpacity>
</View>
);
}
}
export default QrGenerator;
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
margin: 10,
alignItems: "center",
paddingTop: 40,
},
TextInputStyle: {
width: "100%",
height: 40,
marginTop: 20,
borderWidth: 1,
textAlign: "center",
},
button: {
width: "100%",
paddingTop: 8,
marginTop: 10,
paddingBottom: 8,
backgroundColor: "#F44336",
marginBottom: 20,
},
TextStyle: {
color: "#fff",
textAlign: "center",
fontSize: 18,
},
});
What you want to do is to make a random string "inputValue" if it is empty.
getTextInputValue = () => {
if (this.state.inputValue.length === 0) {
const randomInputValue = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
this.setState({
valueForQRCode: randomInputValue,
inputValue: randomInputValue,
});
} else {
this.setState({
valueForQRCode: this.state.inputValue,
});
}
};
I am using the package called react-native-phone-input, and when the phone number is changed it runs the function this.updateInfo() which updates the state. In my code, the icon color is dependent on the state and changes based on whether the phone number is valid. This works, however, when the state is changed, the screen re-renders and the keyboard is dismissed since the text field loses focus. Is there another way I can change the icons color? Or is there a way that I can keep the focus on the text field?
This is what I am referring to:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Keyboard} from 'react-native';
import { Icon } from 'react-native-elements';
import KeyboardAccessory from 'react-native-sticky-keyboard-accessory';
import PhoneInput from 'react-native-phone-input';
export default class PhoneLogin extends Component {
constructor() {
super();
this.state = {
valid: "",
type: "",
value: "",
iconColor: "#D3D3D3",
};
this.updateInfo = this.updateInfo.bind(this);
}
updateInfo() {
this.setState({
valid: this.phone.isValidNumber(),
type: this.phone.getNumberType(),
value: this.phone.getValue().replace(/[- )(]/g,''),
});
}
render() {
return (
<View style={styles.container}>
<PhoneInput
ref={ref => {
this.phone = ref;
}}
style={{height: 50, borderColor:'#44c0b9', borderBottomWidth:2}}
onChangePhoneNumber={ (phone) => {this.updateInfo()} }
/>
<KeyboardAccessory backgroundColor="#fff">
<View style={{ alignItems: 'flex-end', padding:10 }}>
<Icon
raised
reverse
color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"}
name='arrow-right'
type='font-awesome'
onPress={ Keyboard.dismiss()}
/>
</View>
</KeyboardAccessory>
</View>
);
}
}
let styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
padding: 20,
paddingTop: 60
},
info: {
// width: 200,
borderRadius: 5,
backgroundColor: "#f0f0f0",
padding: 10,
marginTop: 20
},
button: {
marginTop: 20,
padding: 10
}
});
In your onPress of your Icon you need to send an arrow function.
The Icon should be like this
<Icon
raised
reverse
color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"
name='arrow-right'
type='font-awesome'
onPress={() => Keyboard.dismiss()}
/>
The problem was the Keyboard.dismiss() was immediately running every time the component re-rendered thus dismissing your keyboard.
Hope this helps!
I'm trying to create a simple React Native app that:
Renders "Hello, [name]!" when a user enters a name (this part works)
Changes the "Hello, [name]!" text color when a button is pressed.
Any ideas as to how I should go about this?
I gave this an initial state of black, but that doesn't even seem to be doing anything.
What I want to happen is to trigger makeRed when the red button is clicked, which will turn the text red. Once I have this working, I'll add more color buttons.
Thank you!
See below for my App.js code. All other files were left in their default state.
import React, { Component } from 'react';
import {
AppRegistry,
Platform,
StyleSheet,
Text,
TextInput,
View,
Button
} from 'react-native';
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
text: 'World',
color: 'black'
};
}
makeRed = () => {
this.setState({
color: 'red'
});
}
render() {
return (
<View style={styles.container}>
<Text style={[styles.welcome, {color: undefined}]}>
Hello, {this.state.text}!
</Text>
<TextInput
style={styles.instructions}
placeholder="Enter a name here!"
onChangeText={(text) => this.setState({text})}
/>
<Button
title='⬤'
onPress={this.makeRed}
color='red'
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 40,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Here's a screenshot of the app for reference:
app screenshot
All you need to do is change this :
style={[styles.welcome, {color: undefined}]}
To
style={[styles.welcome, {color : this.state.color }]}
Please check : WORKING DEMO
color is not referenced as a property of state , in the style of the Text component. Try this as the Text element:
<Text style={{color: this.state.color, ...styles.welcome}}>
Hello, {this.state.text}!
</Text>
And, makeRed needs to be have it's context bound in the constructor, or else this.setState will be undefined. Like this (under super(props)):
this.makeRed = this.makeRed.bind(this)
I am using below versions
react-native-router-flux ^3.39.1
react-native 0.44.0
I expecting that will call API which I am using with "fetch"
Have used componentDidMount but it's showing another error
undefined is not an object (evaluating 'this._component.getScrollableNode')
But I am getting below error outputs
Steps to reproduce
Create three scene using router flux (In my case App, Login, Home)
Use ScrollView for creating the Login.js Create a button
using TouchableHighlight after that call the fetch with a function
using onPress like onPress={ () => this.fetchData() }
Below code, I am using for App.js
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
AsyncStorage,
} from 'react-native';
import Login from './components/Login'
import Register from './components/Register'
import Home from './components/Home'
import { Scene, Router, TabBar, Modal, Schema, Actions, Reducer, ActionConst } from 'react-native-router-flux'
const reducerCreate = params=>{
const defaultReducer = Reducer(params);
return (state, action)=>{
console.log("ACTION:", action);
return defaultReducer(state, action);
}
};
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
logged: false,
loading: true,
};
};
componentWillMount(){
self = this;
AsyncStorage.getItem('token')
.then( (value) =>{
if (value != null){
this.setState({
logged: true,
loading: false,
});
}
else {
this.setState({
loading: false,
})
}
});
};
render() {
if (this.state.loading) {
return <View><Text>Loading</Text></View>;
}
return (
<Router>
<Scene hideNavBar={true} key="root">
<Scene key="logIn" component={Login} title="Login" initial={!this.state.logged}/>
<Scene key="regisTer" component={Register} title="Register"/>
<Scene key="home" component={Home} title="home" initial={this.state.logged}/>
</Scene>
</Router>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
And below code, using for Login.js
/* #flow */
import React, { Component } from 'react';
import {
View,
StyleSheet,
Image,
ScrollView,
TextInput,
Text,
TouchableHighlight,
Alert,
} from 'react-native';
import { Container, Content, InputGroup, Input, Icon, Item } from 'native-base';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import ResponsiveImage from 'react-native-responsive-image'
export default class Login extends Component {
constructor(props){
super(props)
this.state = {
email: '',
password: '',
data: '',
}
}
fetchData() {
fetch('http://allstariq.tbltechnerds.com/api/login/?username=andress&password=23434')
.then((response) => response.json())
.then((responseData) => {
this.setState({
data: responseData.movies,
});
})
.done();
}
render() {
return (
<View style={styles.container}>
<ScrollView>
<View style={ styles.logoContainer }>
<View style={{flexDirection: 'row',}}>
<ResponsiveImage
source={require('../assets/logo.png')}
initWidth="300"
initHeight="160" />
</View>
</View>
<View style={ styles.formContainer }>
<Item>
<Icon active name='mail' />
<Input
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
placeholder='Email'/>
</Item>
<Item>
<Icon active name='key' />
<Input
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
placeholder='Password'/>
</Item>
<TouchableHighlight
style={ styles.loginButton }
onPress={ () => this.fetchData() }>
<Text style={ styles.btnText}>Login</Text>
</TouchableHighlight>
</View>
<View style={ styles.bottomContainer }>
<Text style={ styles.cenText }>Dont worry if you haven't an account yet . . </Text>
<Text
style={ styles.blueText}
onPress={ Actions.regisTer }
>Register Now</Text>
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logoContainer: {
flex: .5,
padding: 10,
justifyContent: 'center',
alignItems: 'center',
},
logoItem: {
width: null,
height: null,
resizeMode: 'cover',
},
formContainer: {
flex: 4,
padding: 10,
},
inputelm: {
marginBottom: 10,
backgroundColor: '#999',
borderWidth: 0,
fontSize: 20,
color: '#FFF',
fontFamily: 'AmaticSC-Bold',
},
loginButton: {
borderRadius: 3,
marginBottom: 20,
marginTop: 20,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
elevation: 4,
},
signupButton: {
borderRadius: 3,
marginBottom: 20,
marginTop: 20,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#7cb342',
elevation: 4,
},
btnText: {
textAlign: 'center',
color: '#FFF',
fontSize: 30,
lineHeight: 40,
},
blueText: {
textAlign: 'center',
color: '#2196f3',
fontSize: 20,
lineHeight: 40,
},
bottomContainer: {
flex: 1,
padding: 10,
},
cenText: {
textAlign: 'center',
fontSize: 16,
},
});
What is the actual way to use fetch with react-native-router-flux? I am new to react, please help me.
well, its a couple of months late but the problem here is that your fetchData method hasn't got access to this because when you declare a method like this:
fetchData() {
}
Under the hood react is creating a function this way:
this.fetchData = function() {
}
when you declare a function using the function keyword, everything between {} will have its own "this" and your method will not have access to the "this" of the component context.
That is the reason why you are getting the "undefined", because you are calling "this.setState" inside the promise returned by fetch, so the error is not fetch, but this.
To solve this issue you could just define your method this way:
fetchData = () => {
}
And because the functions defined with a fat arrow do not create their own scope, the component "this" will be available from inside your method.
Did you try maybe to import the library?
Import fetch from "fetch";
You have not imported the fetch function, import it from the node-fetch module like
import fetch from 'node-fetch'