TextInput onChangeText not working React Native - javascript

i am very new to this platform , it my 2nd day on this. i trying to learn it by myself by creating simple login , sign up , news feed application . i am able to build login page but while getting values from InputText , it display me error saying "Can not specify both value and Children" , Here i am posting my login.js class
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
}
login = () => {
alert(this.state.username + " " + this.state.password);
}
render() {
return (
<View style={styles.container}>
<Image source={require('../images/hulk.jpg')} style={styles.backgroundimage}>
<View style={styles.content}>
<Image source={require('../images/logo.png')} style={styles.logo}>
</Image>
<View style={styles.inputcontainer}>
<TextInput underLineColorAndroid='transparent' style={styles.input} value={this.state.username} onChangeText={(username) => this.setState({ username })} placeholderText='username' > </TextInput>
<TextInput secureTextEntry={true} underLineColorAndroid='transparent' style={styles.input} value={this.state.password} onChangeText={(password) => this.setState({ password })} placeholderText='password' placeholderTextColor='black'> </TextInput>
</View>
<TouchableOpacity onPress={this.login} style={styles.buttonContainer}>
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
</View>
</Image>
</View>
);
}
}
Please let me know where i am going wrong in code
Regards

Can you please try this
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {username: '',password: ''};
}
login = () => {
alert(this.state.username + " " + this.state.password);
}
render() {
return (
<View style={styles.container}>
<Image source={require('../images/hulk.jpg')} style={styles.backgroundimage}>
<View style={styles.content}>
<Image source={require('../images/logo.png')} style={styles.logo}>
</Image>
<View style={styles.inputcontainer}>
<TextInput
underLineColorAndroid='transparent'
style={styles.input}
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })}
placeholderText='username'/>
<TextInput
secureTextEntry={true}
underLineColorAndroid='transparent'
style={styles.input}
value={this.state.password}
onChangeText={(text) => this.setState({ password:text })}
placeholderText='password'
placeholderTextColor='black'/>
</View>
<TouchableOpacity onPress={this.login()} style={styles.buttonContainer}>
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
</View>
</Image>
</View>
);
}

Related

Calling an Input in onPress

I am trying to call my emailInput and have it show up on my createPassword page, specifically where youremail#email.com is. I have given the two pages below, the email page consisting of a user input and the password page where I want that user input to appear on. I cannot really wrap my head around how to refer to the Input in my onPress. Any insight at all is appreciated more than you know!
Also, can I call two onPress's like that? Or do I need to create two functions and do it that way?
SignUpEmail.js
export default class SignUpEmailPage extends Component {
constructor() {
super();
this.state = {
color1: '#A2A2A2'};}
render() {
return (
<View style={styles.containerMain}>
{/* Email Input */}
<Container style = {styles.emailInput}>
<Form>
<Item floatingLabel >
<Label style={{color:this.state.color1}}>Email Address</Label>
<Input
style={styles.textInput}
autoCorrect={false}
autoCapitalize="none"
onFocus={() => this.setState({color1: '#F7018D'})}
onBlur={() => this.setState({color1: '#A2A2A2'})}
/>
</Item>
</Form>
</Container>
<View style={styles.containerBottom}>
<ContinueButton
onPress = {() => navigation.navigate('CreatePassword', { emailInput: })}
onPress={() => this.props.navigation.navigate('CreatePassword')}
/>
</View>
CreatePassword.js
export default class CreatePasswordPage extends Component {
constructor() {
super();
this.state = {
color1: '#A2A2A2'};}
render() {
return (
<View style={styles.containerMain}>
{/* Password Input */}
<Container style = {styles.passwordInput}>
<Form>
<Item floatingLabel>
<Label style={{color:this.state.color1}}>Password</Label>
<Input
style={styles.textInput}
autoCorrect={false}
autoCapitalize="none"
secureTextEntry={true}
onFocus={() => this.setState({color1: '#F7018D'})}
onBlur={() => this.setState({color1: '#A2A2A2'})}
/>
</Item>
</Form>
</Container>
<View style={styles.containerHeader}>
<Text style={styles.title}>Create a Password</Text>
</View>
<View style={styles.containerCaption}>
<Text style={styles.caption}> Lets create your Password for
</Text>
</View>
<View style={styles.containerCaption2}>
<Text style={styles.caption}> youremail#email.com</Text>
</View>
<View style= {styles.backArrowPlacement}>
<BackArrow
onPress={() => this.props.navigation.navigate('SignUpEmail')}
/>
</View>
<View style={styles.containerBottom}>
<ContinueButton
onPress={() => this.props.navigation.navigate('PhoneVerification')}
/>
</View>
</View>
);
}
}
You can't use navigation.navigate as it needs Hooks implementation in the functional component. You can do is
export default class SignUpEmailPage extends Component {
constructor() {
super();
this.state = {
color1: '#A2A2A2',
inputValue: '', // add state here
};
}
updateInputValue = (evt) => {
this.setState({
inputValue: evt.target.value
});
}
render() {
return (
<Input
value = {this.state.inputValue}
onChange={this.updateInputValue }
/>
<ContinueButton
//onPress = {() => navigation.navigate('CreatePassword', { emailInput: })} // remove this
onPress={() => this.props.navigation.navigate('CreatePassword',{ emailInput: this.state.inputValue })} // use this like
/>
)
}
}

Unable to type inside text-input in React Native

I've got the following class:
export default class DonationFormScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
title: this.props.title,
};
}
state = {
units: '0',
comment: '-'
}
render() {
let institution=this.props.route.params.institution;
let title = this.props.route.params.title;
return (
<View>
<View style={styles.container}>
<Text style={styles.label}>¿Cuántas unidades?</Text>
<TextInput
style={styles.input}
placeholder="Unidades..."
onChangeText={(text) => this.setState({units:text})}
/>
<Text style={styles.label}>¿Algún otro comentario?</Text>
<TextInput
style={styles.input}
placeholder="Comentar..."
onChangeText={(text) => this.setState({comment:text})}
/>
<View style={styles.button}>
<Button color="white" title="Donar"/>
</View>
</View>
</View>
);
}
}
Turns out I'm unable to type inside my textinputs. Whenever I click on them I can get the placeholder to disappear and it seems to let me type but nothing gets written on screen.
You didn't give initial value to your Text Input
<TextInput
value={this.state.units}
style={styles.input}
placeholder="Unidades..."
onChangeText={(text) => this.setState({units:text})}
/>
and the same goes for comment TextInput
<TextInput
value={this.state.comment}
style={styles.input}
placeholder="Comentar..."
onChangeText={(text) => this.setState({comment:text})}
/>

React-Native: Formik ref fails to get value

I have a dummy Login code with formik form in react-native
import React, { Component } from "react";
import {
TextInput,
Text,
Alert,
Image,
View,
TouchableOpacity,
SafeAreaView,
ScrollView
} from "react-native";
import styles from "./Styles/LoginStylesheet";
import { KeyboardAccessoryNavigation } from "react-native-keyboard-accessory";
import { Formik } from "formik";
import schemaObject, { initialValues, refs } from "./Validations/LoginValidations";
export default class LoginView extends Component {
constructor(props) {
super(props);
this.state = {
activeInputIndex: 0
};
}
handleFocus = index => () => {
this.setState({
activeInputIndex: index
});
};
handleFocusNext = () => {
if (this.state.activeInputIndex + 1 >= refs.length) {
return;
}
refs[this.state.activeInputIndex + 1].focus();
};
handleFocusPrevious = () => {
if (this.state.activeInputIndex - 1 < 0) {
return;
}
refs[this.state.activeInputIndex - 1].focus();
};
handleLogin = () => {
console.log("ACTIOn");
// this.formik.handleSubmit();
};
render() {
return (
<View style={styles.safeAreaView}>
<SafeAreaView style={styles.safeAreaView}>
<ScrollView style={styles.superView}>
<Formik {/* LINE 56 */}
initialValues={initialValues}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={schemaObject}
ref={p => (this.formik = p)}
>
{({
values,
handleChange,
errors,
setFieldTouched,
touched,
isValid,
handleSubmit
}) => (
<View style={styles.superView}>
<View style={styles.logoParentView}>
<Image
source={require("../../Resources/Assets/Login/aptihealth_logo.png")}
resizeMode={"contain"}
style={styles.logo}
/>
</View>
<View style={styles.emailParentView}>
<Text style={styles.titleLabel}>Email Id</Text>
<TextInput
value={values.emailId}
onChangeText={handleChange("emailId")}
onBlur={() => setFieldTouched("emailId")}
placeholder="Email Id"
style={styles.textInput}
autoCorrect={false}
onFocus={this.handleFocus(0)}
ref={input => {
refs[0] = input;
}}
/>
{touched.emailId && errors.emailId && (
<Text style={{ fontSize: 10, color: "red" }}>
{errors.emailId}
</Text>
)}
</View>
<View style={styles.passwordParentView}>
<Text style={styles.titleLabel}>Password</Text>
<TextInput
value={values.password}
onChangeText={handleChange("password")}
placeholder="Password"
onBlur={() => setFieldTouched("password")}
style={styles.textInput}
autoCorrect={false}
secureTextEntry={true}
onFocus={this.handleFocus(1)}
ref={input => {
refs[1] = input;
}}
/>
{touched.password && errors.password && (
<Text style={{ fontSize: 10, color: "red" }}>
{errors.password}
</Text>
)}
</View>
<View style={styles.forgotPasswordParentView}>
<TouchableOpacity
style={styles.forgotpasswordButton}
activeOpacity={0.7}
>
<Text>Forgot Password?</Text>
</TouchableOpacity>
</View>
<View style={styles.loginParentView}>
<TouchableOpacity
onPress={() => {
console.log("VALUES: ", values, this.formik);
this.handleLogin();
}}
style={styles.loginButton}
activeOpacity={0.7}
>
<Text style={styles.loginText}>Login</Text>
</TouchableOpacity>
</View>
<View style={styles.seperaterParentView}>
<View style={styles.seperaterView} />
<Text style={styles.seperaterText}>OR</Text>
<View style={styles.seperaterView} />
</View>
<View style={styles.faceIdLoginParentView}>
<Image
source={require("../../Resources/Assets/face_id_small_color/face_id_small_color.png")}
resizeMode={"contain"}
/>
<TouchableOpacity style={styles.faceIdButton}>
<Text>Sign In with Face ID</Text>
</TouchableOpacity>
</View>
<View style={styles.signUpParentView}>
<TouchableOpacity style={styles.signupButton}>
<Text>Sign Up for Account Here</Text>
</TouchableOpacity>
</View>
</View>
)}
</Formik>
</ScrollView>
</SafeAreaView>
<KeyboardAccessoryNavigation
nextDisabled={false}
previousDisabled={false}
nextHidden={false}
previousHidden={false}
onNext={this.handleFocusNext}
onPrevious={this.handleFocusPrevious}
avoidKeyboard
/>
</View>
);
}
}
I am trying to console formik ref in login action getting undefined value with debug error
ExceptionsManager.js:126 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `LoginView`.
in Formik (at LoginView.js:56)
I have no idea why it's getting undefined ??
You should take a look at this issue.
You problem is here
<Formik
initialValues={initialValues}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={schemaObject}
ref={p => (this.formik = p)} {/* passing this ref will throw the error */}
>
In the latest version of Formik, they changed Formik to a functional component as explained in the issue, which gives you this error if you pass ref's.
You can check for the suggestions on the issue or wait until they release an update with the correction.
Edit:
Formik made an update and now you can use ref with the prop innerRef.
Please see this comment
You should change it to
<Formik
initialValues={initialValues}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={schemaObject}
{/* using innerRef instead of ref*/}
innerRef={p => (this.formik = p)} {/* this will give you the formik bag */}
>
And this way you can call this.formik.handleSubmit(), just lik you want to do.

Why is KeyboardAvoidingView component not working?

I am trying to make a 1:1 chat, however when I try to tap on the TextInput the KeyboardAvoidingView is not working, I am not sure if this is something with my styles or if I am not using it correctly, here you can find my snack
And this is the code:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
placeholder: 'Write a message...',
text: ''
};
}
render() {
return (
<KeyboardAvoidingView style={{flex: 1, marginTop: 20}} behavior="padding" enabled>
<View style={styles.messageView}>
<Message
message="Hi! First Message"
styleMessage={'one'}
/>
<Message
message="Hi! Second Message"
styleMessage={'two'}
/>
</View>
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
selectionColor={BLUE}
placeholderTextColor={LIGHT_GRAY}
onChangeText={(text) => this.setState({text})}
placeholder={this.state.placeholder}
value={this.state.text}
onEndEditing={() => {console.log(1+1)}}
/>
</View>
<TouchableHighlight style={styles.sendButton}>
<Ionicons name="md-send" size={25} color='#FFFFFF' style={{textAlign: 'center'}}/>
</TouchableHighlight>
</View>
</KeyboardAvoidingView>
);
}
}
in this Context you only need to change
behavior="padding"
for
behavior="height"
and it will starts working correctly on both plataforms (Android/iOS)
Personally I recommend you to use instead KeyboardAwareScrollView from react-native-keyboard-aware-scroll-view package (Link) because it let you configure easier and faster the behavior of it.

React Native - How to pass the Image from the other Component without using React Redux

The goal is to pass the State of the Photos from my CameraRoll.js (Modal) to EventCreator.js(Modal) without using the React Redux. I'm using React Native Navigation V1.
I'm wondering maybe it is possible state of photos: [] become props? Just don't know how to do it. Need help, thank you guys!
Here are my codes:
CameraRoll.js:
state = {
photos: [],
index: null,
pickedImage: null
}
getPhotos = () => {
CameraRoll.getPhotos({
first: 200,
assetType: 'All'
})
.then(res => {
this.setState({
photos: res.edges,
});
})
.catch((err) => {
console.log('Error image: ' + err);
});
};
render() {
return(
<View style={styles.container}>
<Image source={{uri: this.state.pickedImage}} style={styles.image}/>
<ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
{this.state.photos.map((photos, index) => {
return(
<TouchableHighlight
style={{opacity: index === this.state.index ? .5 : 1}}
onPress={() => this.setState({pickedImage: photos.node.image.uri})}
key={index}
underlayColor='transparent'
>
<Image
style={{width: width / 3, height: width /3}}
source={{uri: photos.node.image.uri}}
resizeMode='cover'
/>
</TouchableHighlight>
);
})}
</ScrollView>
</View>
);
}
EventCreator.js:
render(){
return(
<View style={styles.container}>
<EventInput
titleOnChangeText={this.eventNameChangedHandler}
descriptionOnChangeText={this.eventDescriptionChangedHandler}
titleEvent={this.state.controls.eventName}
descriptionEvent={this.state.controls.eventDescription}
/>
<Image
style={styles.image}
source={"I want to pass the image here from CameraRoll.js"}
resizeMode='contain'
/>
</View>
);
}
if you mean this:
onPress={() => this.setState({pickedImage: photos.node.image.uri})}
it just change the state value. What you should do is put an if statement on the return of cameraRoll.js:
private onPress = (img) => {
this.props.onImagePicked(img)
}
render() {
return(
<View style={styles.container}>
<Image source={{uri: this.state.pickedImage}} style={styles.image}/>
<ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
{this.state.photos.map((photos, index) => {
return(
<TouchableHighlight
style={{opacity: index === this.state.index ? .5 : 1}}
onPress={() => this.onPress(photos.node.image.uri))}
key={index}
underlayColor='transparent'
>
<Image
style={{width: width / 3, height: width /3}}
source={{uri: photos.node.image.uri}}
resizeMode='cover'
/>
</TouchableHighlight>
);
})}
</ScrollView>
</View>
);
}
And in EventCreator.js:
constructor(){
super(props);
this.state = {
pickedImg: undefined
}
}
private onImagePicked = (newImg) => {
this.setState({
pickedImg: newImg
})
}
render(){
return(
<View style={styles.container}>
<EventInput
titleOnChangeText={this.eventNameChangedHandler}
descriptionOnChangeText={this.eventDescriptionChangedHandler}
titleEvent={this.state.controls.eventName}
descriptionEvent={this.state.controls.eventDescription}
/>
<Image
style={styles.image}
source={this.props.source}
resizeMode='contain'
/>
<CameraRoll props={...} onImagePicked={this.onImagePicked}/>
</View>
);
}

Categories