How to check a textInput on emptiness - javascript

I need your help. I want to check my textInput for an empty filed, when I am pressing a button. Because now my application can route user to target page with empty fields. So I need to check this fields on emptyness. But I don't know how to do it. I will be very glad, if you help me.
This is my component
import React, { Component } from 'react'
import { View, TextInput } from 'react-native'
import { MyButton, ErrorMessage } from '../uikit'
import { FormStyle, InputStyle } from '../constants/styles'
import { LOG_IN } from '../routes'
export class SignIn extends Component {
state = {
isValidPasword: true,
isEqual: true,
isValidMail: true,
currentPassword: ''
}
isEnoughSymbols = (text) => {
if (text.trim().length < 8) {
this.setState({ isValidPasword: false })
}
else {
this.setState({ currentPassword: text, isValidPasword: true })
}
}
isMatch = (text) => {
if (text != this.state.currentPassword) {
this.setState({ isEqual: false })
}
}
isMail = (text) => {
const pattern = /\b[a-z0-9._]+#[a-z0-9.-]+\.[a-z]{2,4}\b/i
let res = text.search(pattern)
res == -1 ? this.setState({ isValidMail: false }) : this.setState({ isValidMail: true })
}
render() {
const { mainContainer, buttons } = FormStyle
const { container, text } = InputStyle
const { isValidPasword, isEqual, isValidMail, currentPassword } = this.state
return (
<View style={mainContainer}>
<View style={container}>
<TextInput
style={text}
placeholder={'Email'}
onEndEditing={(e) => this.isMail(e.nativeEvent.text)}
>
</TextInput>
{
isValidMail ? null : <ErrorMessage errorText={'Invalid email!'} />
}
</View>
<View style={container}>
<TextInput
style={text}
placeholder={'Password'}
secureTextEntry={true}
onEndEditing={(e) => this.isEnoughSymbols(e.nativeEvent.text)}
>
</TextInput>
{
isValidPasword ? null : <ErrorMessage errorText={'Password must have at least 8 symbols!'} />
}
</View>
<View style={container}>
<TextInput
style={text}
secureTextEntry={true}
placeholder={'Confirm password'}
>
</TextInput>
{
isEqual ? null : <ErrorMessage errorText={'Passwords not matching'} />
}
</View>
<View style={buttons}>
<MyButton
name={'confirm'.toUpperCase()}
onPress={() => (isEqual && isValidMail && isValidPasword) ? this.props.navigation.navigate(LOG_IN) : alert('Your data is wrong!')} />
</View>
</View>
)
}
}

Set the value of the text input using state.
E.g.
state = {
/// rest of state
textValue: ""
}
In the TextInput component add a function to set the state onChange, so the textValue changes when the user types, e.g. (e) => this.setState({ textValue: e.nativeEvent.text })
Then you can check if the input is empty with a function that checks for the state value, like if(this.textValue === "") and then handle the empty vs. not-empty condition.

Better way you can make function like this to check empty spaces, Blank value and text length.
function isEmpty(isFieldEmpty) {
isFieldEmpty = isFieldEmpty.trim()
if (!isFieldEmpty || isFieldEmpty == "" || isFieldEmpty.length <= 0) {
return true;
}
else {
return false;
}
}

Related

Get data from multiple custom checkboxes in react native

I am building a small quiz in react native. On my screen, I want the user to chose several correct answers from a choice of 4-6 options. I build a custom checkbox for that. If the correct answers are checked (and all wrong answers are unchecked) the user should get a message that the answer was correct.
Here is the custom checkbox component. I only included the code for three boxes to make the code a bit shorter:
import { TouchableOpacity, StyleSheet, View, Text } from "react-native";
import { FontAwesome } from "#expo/vector-icons";
function AnswerContainer_CheckBox(props) {
const [userInput, setUserInput] = useState("");
const answerHandler = () => {
if (userInput == props.finalAnswer) {
dispatch(answerTrue());
}
};
const [checked_1, setChecked_1] = useState(false);
const [checked_2, setChecked_2] = useState(false);
const [checked_3, setChecked_3] = useState(false);
/*Visibility
if set to false via props, the checkbox won't show
*/
const [box_1_Visibility, setBox_1_Visibility] = useState(
props.box_1_Visibility
);
const [box_2_Visibility, setBox_2_Visibility] = useState(
props.box_2_Visibility
);
const [box_3_Visibility, setBox_3_Visibility] = useState(
props.box_3_Visibility
);
/* Functions to chech and uncheck ityems*/
const checkedHandler_1 = () => {
if (checked_1 == false) {
setChecked_1(true);
setUserInput(userInput + props.box_1_Letter);
answerHandler();
} else {
setChecked_1(false);
setUserInput(userInput.replace(props.box_1_Letter,""));
answerHandler();
}
};
const checkedHandler_2 = () => {
if (checked_2 == false) {
setChecked_2(true);
setUserInput(userInput + props.box_2_Letter);
answerHandler();
} else {
setChecked_2(false);
setUserInput(userInput.replace(props.box_2_Letter,""));
answerHandler();
}
};
const checkedHandler_3 = () => {
if (checked_3 == false) {
setChecked_3(true);
setUserInput(userInput + props.box_3_Letter);
answerHandler();
} else {
setChecked_3(false);
setUserInput(userInput.replace(props.box_4_Letter,""));
answerHandler();
}
};
return (
<View>
{/* Checkbox 1 */}
<TouchableOpacity
onPress={() => {
checkedHandler_1();
}}
>
<View
style={
(box_1_Visibility === true && styles.mainContainer) || styles.hide
}
>
<View style={styles.icon}>
<FontAwesome
name={checked_1 == true ? "check-square" : "square-o"}
size={24}
color={checked_1 == true ? "#3787FF" : "#BFD3E5"}
/>
</View>
<Text style={styles.checkButtonText}>{props.box_1_Label}</Text>
</View>
</TouchableOpacity>
{/* Checkbox 2 */}
<TouchableOpacity
onPress={() => {
checkedHandler_2();
}}
>
<View
style={
(box_2_Visibility === true && styles.mainContainer) || styles.hide
}
>
<View style={styles.icon}>
<FontAwesome
name={checked_2 == true ? "check-square" : "square-o"}
size={24}
color={checked_2 == true ? "#3787FF" : "#BFD3E5"}
/>
</View>
<Text style={styles.checkButtonText}>{props.box_2_Label}</Text>
</View>
</TouchableOpacity>
{/* Checkbox 3 */}
<TouchableOpacity
onPress={() => {
checkedHandler_3();
}}
>
<View
style={
(box_3_Visibility === true && styles.mainContainer) || styles.hide
}
>
<View style={styles.icon}>
<FontAwesome
name={checked_3 == true ? "check-square" : "square-o"}
size={24}
color={checked_3 == true ? "#3787FF" : "#BFD3E5"}
/>
</View>
<Text style={styles.checkButtonText}>{props.box_3_Label}</Text>
</View>
</TouchableOpacity>
</View>
);
}
So what is happening here: onPress the checkedHandler-function checks the state. If "false" it will change it to "true". If it is "true" it will change to "false". Depending on the state, the style of the checkbox will change. The checkedHandler-function will also update the string within "userInput" depending on the state. The content of the string is catched via props from the parent component ("box_1_Letter" etc).
This is how I added the component in my screen/parent component:
<AnswerContainer_CheckBox
finalAnswer={"AC"}
box_1_Visibility={true}
box_2_Visibility={true}
box_3_Visibility={true}
box_4_Visibility={true}
box_5_Visibility={false}
box_6_Visibility={false}
box_1_Label={"Shanghai"}
box_1_Letter={"A"}
box_2_Label={"Paris"}
box_2_Letter={"B"}
box_3_Label={"New York"}
box_3_Letter={"C"}
box_4_Label={"Berlin"}
box_4_Letter={"D"}
/>
As you can see I first define how many boxes should be visible and I also add a label to each box and the associated "letter". "finalAnswer" contains the correct answer.
Now comes my problem: let's say in my example "Shanghai" and "New York" are the correct answers. Both boxes have to be checked while all other boxes have to be unchecked. How do I check that within the parent component/Screen?. My solution does not work. The user would have to check the boxes in the right order (and even then it somehow didn't work). The solution would also only be available within the component, not the parent. I do not want to create a global state with redux for this.
Any help appreciated (be aware: I am pretty new to this :-)
this modified answerHandler should solve your problem
const answerHandler = () => {
// if input length equals result length
if (userInput.length === props.finalAnswer.length) {
const inclusionMap = Array.from(props.finalAnswer).map((char) => {
return userInput.includes(char);
});
// if all the characters are included
if (inclusionMap.every((bool) => bool === true)) {
dispatch(answerTrue());
}
}
};

How to fire two functions on single button click

Hello stackoverflow community I am having problem in using onpress method. Actually i want to fire two functions on a single button click like if i press Register button the validate() function and userRegister function works first validate function validate all the fields and then register function registers user into db. I seen setState is responsible for this kind of behaviour since i m new in react native development so i cant implement this kind of functionality
my code :
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
ToastAndroid.show('User Registration Sucessfull', ToastAndroid.SHORT)
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={this.Validate}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
Pass the validate function to onPress = {()=> this.validate()}
And then pass the UserRegistrationFunction in validate function at the end.
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
this.UserRegistrationFunction();
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={()=>this.Validate()}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
As i mentioned below, You can call two function like this (in class component)
login=()=>{
console.log('login')
}
register =()=>{
console.log('register')
}
<Button title = "Next" onPress={()=>[this.user(),this.register()]}/>
According to your requirement, You should use something like this.
import React, { Component } from 'react';
import {
Alert,
View,
Text,
Image,
TouchableOpacity,
Button,
TextInput,
} from 'react-native';
class HomeScreen extends Component {
state = {
date: '',
month: '',
year: '',
isErrorDate: false,
isErrorDateLenght: false,
isErrorMonth: false,
isErrorMonthLength: false,
isErrorYear: false,
isErrorYearLength: false,
};
onChangeDate = value => {
this.setState({
date: value,
isErrorDate: false,
isErrorDateLenght: false,
});
};
onChangeMonth = value => {
this.setState({
month: value,
isErrorMonth: false,
isErrorMonthLength: false,
});
};
onChangeYear = value => {
this.setState({
year: value,
isErrorYear: false,
isErrorYearLength: false,
});
};
doRegister = () => {
console.log('you have registered');
};
checkDate = () => {
//validation part or function
const { date, month, year } = this.state;
let isErrorDate = date.trim() === '' ? true : false;
let isErrorDateLenght =
date.length > 2 || !/^[0-9]+$/.test(date) || date > 31 ? true : false;
let isErrorMonth = month.trim() === '' ? true : false;
let isErrorMonthLength =
month.length > 2 || !/^[0-9]+$/.test(month) || month > 12 ? true : false;
let isErrorYear = year.trim() === '' ? true : false;
let isErrorYearLength =
year.length > 4 || !/^[0-9]+$/.test(year) ? true : false;
if (
isErrorDate ||
isErrorDateLenght ||
isErrorMonth ||
isErrorMonthLength ||
isErrorYear ||
isErrorYearLength
) {
this.setState({
isErrorDate: isErrorDate,
isErrorDateLenght: isErrorDateLenght,
isErrorMonth: isErrorMonth,
isErrorMonthLength: isErrorMonthLength,
isErrorYear: isErrorYear,
isErrorYearLength: isErrorYearLength,
});
Alert.alert('invalid date /month/ year');
} else {
//submit date and call other functions
this.doRegister();
}
};
render() {
return (
<View style={{ flex: 1 }}>
<View>
<View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="DD"
keyboardType="number-pad"
value={this.state.date}
onChangeText={this.onChangeDate}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="MM"
keyboardType="number-pad"
value={this.state.month}
onChangeText={this.onChangeMonth}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="AA"
keyboardType="number-pad"
value={this.state.year}
onChangeText={this.onChangeYear}
/>
</View>
</View>
</View>
<View>
<Button title ="Next" onPress={this.checkDate}/>
</View>
</View>
);
}
}
export default HomeScreen;
Change this according to your requirement. Feel free for doubts

React-native- conditionally Disable TouchableHighlight if array is empty

I want to disable TouchableHighlight if my array is empty and turn it back to enable if my array has value.
this.state = {
modalVisible: false,
array:[],
}
}
toggleModal(visible) {
this.setState({modalVisible: visible})
}
<TouchableHighlight
underlayColor="transparent"
onPress = {() => {
if(this.state.array == undefined || this.state.array.length == 0){
this.toggleModal(this.state.modalVisible)}
else {
this.toggleModal(!this.state.modalVisible)}
}}>
<Text>close</Text>
</TouchableHighlight>
Above is my code. I think I have it right but its not working. Any advise or comments would be really appreciated.
You can do this
this.state =
{
modalVisible: false,
array: []
}
toggleModal = visible => this.setState({modalVisible: visible})
render = () =>
{
return (
<TouchableHighlight
underlayColor="transparent"
disabled={this.state.array.length === 0}
onPress = {() =>
{
if(this.state.array == undefined || this.state.array.length == 0)
this.toggleModal(this.state.modalVisible);
else
this.toggleModal(!this.state.modalVisible);
}}>
<Text>close</Text>
</TouchableHighlight>
);
}

Add value of checkbox to an array when it is clicked

I have this situation where I want to transfer userid to an array which is defined in State.
I want to do it when I click on the checkbox to select it, and I want to remove the userid from the array when I deselect the checkbox
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
AsyncStorage
} from "react-native";
import axios from 'axios';
import { Button, Container, Content, Header, Body, Left, Right, Title } from 'native-base';
import Icon from 'react-native-vector-icons/Ionicons';
import { List, ListItem, SearchBar, CheckBox } from "react-native-elements";
// const itemId = this.props.navigation.getParam('itemId', 'NO-ID');
// const otherParam = this.props.navigation.getParam('otherParam', 'some default value');
class TeacherSubjectSingle extends Component{
static navigationOptions = {
header : null
}
// static navigationOptions = {
// headerStyle: {
// backgroundColor: '#8E44AD',
// },
// headerTintColor: '#fff',
// }
state = {
class_id: null,
userid: null,
usertype: null,
student_list: [],
faq : [],
checked: [],
}
componentWillMount = async () => {
const {class_id, student_list, userid, usertype} = this.props.navigation.state.params;
await this.setState({
class_id : class_id,
student_list : student_list,
userid : userid,
usertype : usertype,
})
console.log(this.state.class_id)
var result = student_list.filter(function( obj ) {
return obj.class_section_name == class_id;
});
this.setState({
student_list: result[0]
})
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE",
}}
/>
);
};
checkItem = (item) => {
const { checked } = this.state;
console.log(item)
if (!checked.includes(item)) {
this.setState({ checked: [...checked, item] });
} else {
this.setState({ checked: checked.filter(a => a !== item) });
}
console.log(checked)
};
render(){
return (
<Container>
<Header style={{ backgroundColor: "#8E44AD" }}>
<Left>
<Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
<Icon name="ios-arrow-dropleft" size={24} color='white' />
</Button>
</Left>
<Body>
<Title style={{ color: "white" }}>{this.state.class_id}</Title>
</Body>
<Right>
{this.state.checked.length !== 0 ? <Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
<Text>Start Chat</Text>
</Button> : null}
</Right>
</Header>
<View style={{flex: 1, backgroundColor: '#fff'}}>
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.state.student_list.students}
extraData={this.state.checked}
renderItem={({ item }) => (
<ListItem
// roundAvatar
title={<CheckBox
title={item.name}
checkedColor='#8E44AD'
onPress={() => this.checkItem(item.userid)}
checked={this.state.checked.includes(item.userid)}
/>}
// subtitle={item.email}
// avatar={{ uri: item.picture.thumbnail }}
//containerStyle={{ borderBottomWidth: 0 }}
onPress={()=>this.props.navigation.navigate('IndividualChat', {
rc_id: item.userid,
userid: this.state.userid,
usertype: this.state.usertype,
subject_name: this.state.student_list.subject_name
})}
/>
)}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>
</List>
</View>
</Container>
);
}
}
export default TeacherSubjectSingle;
const styles = StyleSheet.create({
container:{
flex:1,
alignItems:'center',
justifyContent:'center'
}
});
this is the code for the same, I have created a function checkItem()for the same and it is working, the only problem is, when I click on the first item, it will output the blank array, I select the second item and it will return the array with first item and so on. Please help me resolve it, thanks in advance
Its because you are printing this.state.checked value just after the setState, setState is async, it will not immediately update the state value.
You can use setState callback method to check the updated state values.
Write it like this:
checkItem = (item) => {
const { checked } = this.state;
let newArr = [];
if (!checked.includes(item)) {
newArr = [...checked, item];
} else {
newArr = checked.filter(a => a !== item);
}
this.setState({ checked: newArr }, () => console.log('updated state', newArr))
};
Check this answer for more details about setState:
Why calling setState method doesn't mutate the state immediately?
Try below code:
checkItem = (e) => {
let alreadyOn = this.state.checked; //If already there in state
if (e.target.checked) {
alreadyOn.push(e.target.name); //push the checked value
} else {
//will remove if already checked
_.remove(alreadyOn, obj => {
return obj == e.target.name;
});
}
console.log(alreadyOn)
this.setState({checked: alreadyOn});
}
Like this, with an event listener and the .push method of an array.
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var myArray = [];
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("click", function(e) {
myArray.push(e.target.value);
console.log(myArray);
});
};
<div>
<input type="checkbox" name="feature" value="scales" />
<label >Scales</label>
</div>
<div>
<input type="checkbox" name="feature" value="horns" />
<label >Horns</label>
</div>
<div>
<input type="checkbox" name="feature" value="claws" />
<label >Claws</label>
</div>

Input react native - press in crashes application

When press input text to 3 seconds, show the message "Application name is stopped", how to correct this?...........................................................................................
my component
return (
<ReactNative.TextInput
ref={(ref: any) => { this.input = ref; }}
style={styleInputFormDefault}
numberOfLines={this.state.numberOfLines}
blurOnSubmit={true}
editable={this.state.editable}
underlineColorAndroid={"transparent"}
value={this.state.value}
multiline={this.state.multiline}
placeholder={this.state.placeholder}
keyboardType="default"
onChange={event => {
this.value = event.nativeEvent.text;
}}
onEndEditing={event => {
this.value = event.nativeEvent.text;
if (this.props.onChange != undefined) {
!this.props.onChange(this.value);
}
}}
returnKeyType={this.state.returnKeyType}
onSubmitEditing={() => {
if (this.props.onSubmit != undefined) {
this.props.onSubmit(this);
}
}}
onFocus={() => {
if (this.props.onFocus != undefined) {
this.props.onFocus();
};
}}
onBlur={() => {
if (this.props.onBlur != undefined) {
this.props.onBlur();
};
}}
>
</ReactNative.TextInput>
);
Try this fix - https://github.com/facebook/react-native/issues/17530
This fix is already available in a higher version of. react-native now - https://github.com/facebook/react-native/pull/24183/commits/6310ad1e9441d532f930eb89e38300dbd973a919
Why are using the TextInput component like that? Simply import just the TextInput from react native.
Try this code:
import React, { Component } from 'react'
import { TextInput } from 'react-native'
export default class InputClassName extends Component {
constructor(props) {
super(props)
this.input = null
this.state {
[...]
}
}
render() {
return(
<View>
<TextInput
ref={ref => this.input = ref}
style={styleInputFormDefault}
numberOfLines={this.state.numberOfLines}
blurOnSubmit={true}
underlineColorAndroid={"transparent"}
value={this.state.value}
multiline={this.state.multiline}
placeholder={this.state.placeholder}
keyboardType="default"
onChangeText={value => this.value = value}
onEndEditing={event => {
// I do not know what you're trying to do here
// Are you checking if the onChange props is a function? If so, do this instead:
// if("function" === typeof this.props.onChange) { [...] }
this.value = event.nativeEvent.text;
if (this.props.onChange != undefined) {
!this.props.onChange(this.value);
}
}}
returnKeyType={this.state.returnKeyType}
onSubmitEditing={() => {
// same goes here
if (this.props.onSubmit != undefined) {
this.props.onSubmit(this);
}
}}
onFocus={() => {
// also here
if (this.props.onFocus != undefined) {
this.props.onFocus();
};
}}
onBlur={() => {
// and here.
if (this.props.onBlur != undefined) {
this.props.onBlur();
};
}}
>
</TextInput>
{ /* Please note that you can also use propTypes in order to force (recommended)
a specific prop to be the typeof whatever you want instead of using if/else */ }
</View>
)
}
}

Categories

Resources