React Native - text disappearing on custom component style change - react-native

Getting a strange error when trying to apply conditional styling to a custom component. Whenever the style change should appear the text completely disappears. If I start typing again, the new styling appears but once the style would change again, the text disappears again. If I apply the styling as static, the custom styling works completely fine. I'm not sure what the issue could be. Thanks in advance for the help.
<UserInput
style = {!this.state.isValidEmail ? styles.errorInline : styles.default}
placeholder="Email"
autoCapitalize={'none'}
returnKeyType={'next'}
autoCorrect={false}
onSubmitEditing={() => this.focusNextField('password')}
updateState={(email) => {
let formattedEmail = email.trim();
this.state.initialValidationChecked? this.validate(formattedEmail) : this.setState({formattedEmail})}
}
blurOnSubmit={true}
onBlur2={(event) => this.validate(event.nativeEvent.text.trim())}
/>
errorInline: {
color: 'red',
},
default : {
color: '#777777'
}
export default class UserInput extends Component {
componentDidMount() {
if (this.props.onRef != null) {
this.props.onRef(this)
}
}
onSubmitEditing() {
if(this.props.onSubmitEditing){
this.props.onSubmitEditing();
}
}
focus() {
this.textInput.focus();
}
render() {
return (
<View style={styles.inputWrapper}>
<TextInput
style={[styles.input, this.props.style]}
placeholder={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
onChangeText={(value) => this.props.updateState(value)}
onEndEditing={(value) => { if(this.props.onBlur2) return this.props.onBlur2(value)}}
ref={input => this.textInput = input}
blurOnSubmit={this.props.blurOnSubmit}
onSubmitEditing={this.onSubmitEditing.bind(this)}
underlineColorAndroid='transparent'
/>
</View>
);
}
}
UserInput.propTypes = {
placeholder: PropTypes.string.isRequired,
secureTextEntry: PropTypes.bool,
autoCorrect: PropTypes.bool,
autoCapitalize: PropTypes.string,
returnKeyType: PropTypes.string,
};
const DEVICE_WIDTH = Dimensions.get('window').width;
const styles = StyleSheet.create({
input: {
width: DEVICE_WIDTH - 70,
height: 40,
marginHorizontal: 20,
marginBottom: 30,
color: '#777777',
borderBottomWidth: 1,
borderBottomColor: '#0099cc'
},
inputWrapper: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
});

Styles are given as object (key-value pair).
But looking at your codes in the following line
style = {!this.state.isValidEmail ? styles.errorInline : 'none'}
When this.state.isValidEmail returns true, you're just giving 'none' to the style, which is a syntax error, you should return something like this
style = {!this.state.isValidEmail ? styles.errorInline : {display: 'none'}}

Related

FlatList show according to TextInput handle

I have Dynamic form in which user can add form and remove form when user start typing on first form TextInput it will give suggestion as per input. Now the problem is when user start typing on first TextInput field it will get suggestion but when user add another form by clicking on addForm Button and when user start typing on new form it will get suggestion but on same time in the first form it also start giving suggestion and same if there is three form it will start giving suggestion for all three form if user start typing in one form.I want to say that If user type any of form it will give suggestion on all form.
I want like if user is on first form then it will give suggestion only for first form not for second form as well. if user is on second form it will only get suggestion on second form not on first as well.
You can see in above picture it is giving suggestion for both form even if I'm typing on second form
import React, { PureComponent } from 'react'
import {
View,
TextInput,
ScrollView,
KeyboardAvoidingView,
StyleSheet,
Picker,
ListView,
FlatList
} from 'react-native'
import { getStockItems } from "../../actions/getIndentsAction";
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { CardSection, Text, Button, Block, Input } from '../../components';
import { theme } from '../../constants';
import { MaterialIcons,AntDesign,Entypo } from '#expo/vector-icons';
import { CardItem,Content, ListItem,Icon,Card, Left, Body, Right } from 'native-base';
class IndentForm extends PureComponent {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerRight: (
<TouchableOpacity onPress={() => params.handleSave()}>
<AntDesign
name='plus'
style={{ paddingRight:10}}
size={25}
color='white'
/>
</TouchableOpacity>
)
};
};
constructor(props) {
super(props);
this.state = {
companyName:'',
formFields:[{
Item_Description:'',
Quantity:'',
}],
searchedForm:[]
};
}
componentDidMount() {
this.props.navigation.setParams({ handleSave: this.addInput});
this.props.getStockItems()
}
//add dynamic form
addInput = () => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
const allFormFieldsAfterAddingNew = [...existingFormFields, {Item_Description: '', Quantity:''}]
this.setState({formFields: allFormFieldsAfterAddingNew})
}
//remove dynamic form
removeInput = index => () => {
this.setState({
formFields: this.state.formFields.filter((s, sidx) => index !== sidx)
});
};
//on Item Descriptionchange
onItemDescriptionChange = (text, index) => {
const { stocks } = this.props.indent;
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Item_Description = text
existingFormFields[index] = targetField
var searchedForm = stocks.filter(function(stock) {
return stock.Item.toLowerCase().indexOf(text.toLowerCase()) > -1;
});
this.setState({searchedForm: searchedForm , formFields: existingFormFields})
}
//on Quantity change
onQuantityChange = (text, index) => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Quantity = text
existingFormFields[index] = targetField
this.setState({formFields: existingFormFields})
}
itemSelect = (item,index) => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Item_Description = item.Item
existingFormFields[index] = targetField
this.setState({searchedForm:[], formFields:existingFormFields})
console.log("hello" + " " + item.Item + " " + index);
}
onsubmit = () => {
const data = {
companyName:this.state.companyName,
formFields:this.state.formFields
}
console.log(data)
}
render() {
const { stocks } = this.props.indent;
return (
<KeyboardAvoidingView style={{flex:1, justifyContent:"center"}} behavior="padding">
<ScrollView
showsVerticalScrollIndicator={false}
>
<Block padding={[5]}>
<Card>
<Picker
style={{flex:1}}
selectedValue={this.state.companyName}
onValueChange={(companyName)=>this.setState({companyName:companyName})}
>
<Picker.Item label='developer' value="0" />
<Picker.Item label="Developer" value="Developer" />
<Picker.Item label="Junior Develope" value="Junior Develope" />
</Picker>
</Card>
{
this.state.formFields.map((field, index) => {
return(
<Card key={index} >
<CardItem bordered>
<Left>
<Text bold>Items no : {index + 1}</Text>
</Left>
<Right>
<TouchableOpacity
onPress={this.removeInput(index)}
>
<Entypo
name="cross"
size={20}
color='#E46932'
/>
</TouchableOpacity>
</Right>
</CardItem>
<Block padding={[0, theme.sizes.base]}>
<Block>
<Input
label="description"
style={[styles.input]}
value={field.Item_Description}
onChangeText={(text)=> this.onItemDescriptionChange(text, index)}
/>
<FlatList
data={this.state.searchedForm}
keyExtractor={(ItemId,index) => index.toString()}
renderItem={({item,index})=>(
<ListItem
button={true}
key={index}
onPress={()=>this.itemSelect(item,index)}
>
<Text bold>{item.Item}</Text>
</ListItem>
)}
/>
</Block>
<Input
label="Quantity"
style={[styles.input]}
value={field.Quantity}
onChangeText={(text)=> this.onQuantityChange(text, index)}
/>
</Block>
</Card>
)
})
}
<Block padding={[0, theme.sizes.base * 1.5]}>
<Button
style={styles.submitInput}
onPress={this.onsubmit}>
<Text bold white center>Submit</Text>
</Button>
</Block>
</Block>
</ScrollView>
</KeyboardAvoidingView>
)
}
}
IndentForm.propTypes = {
getStockItems: PropTypes.func.isRequired,
indent: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
indent: state.indent,
errors:state.errors
});
export default connect(
mapStateToProps,
{
getStockItems,
}
)(IndentForm);
const styles = StyleSheet.create({
input: {
borderRadius: 0,
borderWidth: 0,
borderBottomColor: theme.colors.gray2,
borderBottomWidth: StyleSheet.hairlineWidth,
marginLeft:5
},
submitInput:{
backgroundColor:"#2ecc71"
},
addInput:{
backgroundColor:"white"
},
addButton:{
alignItems:"flex-end",
position:"absolute",
right:20,
bottom:20,
},
searchBarContainerStyle: {
marginBottom: 10,
flexDirection: "row",
height: 40,
shadowOpacity: 1.0,
shadowRadius: 5,
shadowOffset: {
width: 1,
height: 1
},
backgroundColor: "rgba(255,255,255,1)",
shadowColor: "#d3d3d3",
borderRadius: 10,
elevation: 3,
marginLeft: 10,
marginRight: 10
},
selectLabelTextStyle: {
color: "#000",
textAlign: "left",
width: "99%",
padding: 10,
flexDirection: "row"
},
placeHolderTextStyle: {
color: "#D3D3D3",
padding: 10,
textAlign: "left",
width: "99%",
flexDirection: "row"
},
dropDownImageStyle: {
marginLeft: 10,
width: 10,
height: 10,
alignSelf: "center"
},
pickerStyle: {
marginLeft: 18,
elevation:3,
paddingRight: 25,
marginRight: 10,
marginBottom: 2,
shadowOpacity: 1.0,
shadowOffset: {
width: 1,
height: 1
},
borderWidth:1,
shadowRadius: 10,
backgroundColor: "rgba(255,255,255,1)",
shadowColor: "#d3d3d3",
borderRadius: 5,
flexDirection: "row"
}
})
when you do addInput, it adds new FlatList for each input. but, data of FlatList is managed by single state which is this.state.searchedForm.
So whenever onItemDescriptionChange gets called, it updates the searchedForm state and all the FlatList reflects that change.
To resolve this, either you'll have to keep the FlatList data inside formFields state as one key or you can manage different state for each input.

Handling focus in react native with multiple input

I am looking to only toggle the focus state on one of the inputs instead of both when onFocus is fired.
With both inputs having the 'onFocus' and 'onBlur' events I was expecting the state to update on only the current element that is focussed.
Should I be using refs instead of state for this sort of event handling?
class SignInScreen extends Component {
state = {
isFocused: false,
style: {
inputContainer: styles.input
}
}
onFocus = () => {
if(!this.state.isFocused) {
this.setState({
isFocused: true,
style: {
inputContainer: styles.inputDifferent
}
})
}
}
onBlur = () => {
if(this.state.isFocused) {
this.setState({
isFocused: false,
style: {
inputContainer: styles.input
}
})
}
}
render() {
return (
<Input
containerStyle={[styles.input, this.state.style.inputContainer]}
onFocus={this.onFocus}
onBlur={this.onBlur}
/>
<Input
containerStyle={[styles.input, this.state.style.inputContainer]}
onFocus={this.onFocus}
onBlur={this.onBlur}
/>
)
}
}
const styles = StyleSheet.create({
input: {
borderWidth: 1,
borderColor: 'white,
marginBottom: 16,
maxWidth: '90%',
marginLeft: 'auto',
marginRight: 'auto'
},
inputDifferent: {
backgroundColor: 'gray',
}
});
Modify your code Like This:
Edited:
class SignInScreen extends Component {
state = {
isFocused: false,
firstLoad: true
}
onFocus = () => {
this.setState({
isFocused: !this.state.isFocused,
firstLoad: false
})
}
render() {
const {isFocused} = this.state
return (
<View>
<Input
containerStyle={isFocused || firstLoad ? styles.input : styles.inputDifferent}
onFocus={this.onFocus}
/>
<Input
containerStyle={!isFocused || firstLoad ? styles.input : styles.inputDifferent}
onFocus={this.onFocus}
/>
</View>
)
}
}
const styles = StyleSheet.create({
input: {
borderWidth: 1,
borderColor: 'white',
marginBottom: 16,
maxWidth: '90%',
marginLeft: 'auto',
marginRight: 'auto'
},
inputDifferent: {
backgroundColor: 'gray',
}
});
its unnecessary to include styles on state. it is better to only use this.state.isFocus to make code simplier. just used this to make a condition on what style the inputs will be using.
you can also disregard onBlur. because all we need on the conditions is isFocus.
the key factor here is the exclamation symbol that will make the state toggle.
Edited: firstLoad state added to make the style of both inputs the same on load. that will be used on the condition inside input styles.
note: it can only work with two inputs

How to add a text input to alert in react native

Can someone help with adding a text input to an alert in react native. Is it possible? I searched and found results that deals with multiple line text input which is not the case with me. Thanks in advance
This is possible. I believe this was only available initially for AlertIOS however it seems to have been intergrated to React Native Alert.
Edit: Although its added to Alert it does not seem to work for Android
Use
import { Alert } from 'react-native';
onButtonPress = () => {
Alert.prompt(
"Enter password",
"Enter your password to claim your $1.5B in lottery winnings",
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{
text: "OK",
onPress: password => console.log("OK Pressed, password: " + password)
}
],
"secure-text"
);
};
}
More details: https://reactnative.dev/docs/alertios
Use react-native-dialog it works across platform and is simple enough.
There is no way you could add a text input to the Alert component according to the documentation, You will need to create a custom component by yourself in order to achieve that, example: use customise modal or use react-native-simple-dialogs
No way
Just use custom modal or third party library to achieve this...
Here is a spoiler using a custom Modal:
import React, { FC } from 'react'
import { View, TextInput, Modal, GestureResponderEvent } from 'react-native';
import { BoldText, IOSButton } from '..';
import { colors } from '../../constants';
import { customModalStyles, defaultStyles } from '../../styles';
interface Props {
modalVisible: boolean;
// onRequestClose,
textOne: string;
buttonOneTitle: string;
onPressOne: (event: GestureResponderEvent) => void;
value: string,
onChangeText: (text: string) => void;,
placeholder: string
}
const InputModal: FC<Props> = ({
modalVisible,
// onRequestClose,
textOne,
buttonOneTitle,
onPressOne,
value,
onChangeText,
placeholder
}) => {
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
// onRequestClose={onRequestClose}
>
<View style={customModalStyles.centeredView}>
<View style={customModalStyles.modalView}>
<BoldText
style={customModalStyles.textSize}>{textOne}
</BoldText>
<TextInput
secureTextEntry
autoCapitalize="none"
style={[
defaultStyles.inputStyle,
defaultStyles.textInputShadow,
]}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.placeHolder}
/>
<IOSButton title={buttonOneTitle}
onPress={onPressOne}
/>
</View>
</View>
</Modal>
)
}
export default InputModal;
And the styles:
import { StyleSheet } from 'react-native';
import { colors } from '../constants';
import styleConstants from './styleConstants';
const customModalStyles = StyleSheet.create({
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
centeredView: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
marginBottom: 20,
},
modalView: {
justifyContent: 'space-around',
alignItems: 'center',
width: styleConstants.width < 1000 ? 320 : 400,
height: styleConstants.height < 1000 ? 320 : 400,
backgroundColor: colors.primary,
borderRadius: 20,
paddingHorizontal: 15,
paddingTop: 10,
shadowColor: colors.secondary,
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.55,
shadowRadius: 8,
elevation: 20,
},
textSize: {
textAlign: 'center',
fontSize: styleConstants.fontSizeSM,
},
});
export default customModalStyles;
Then one may use it like this:
{modalVisible && (
<InputModal
modalVisible={modalVisible}
textOne={`...`}
buttonOneTitle="..."
onPressOne={async () => {
setModalVisible(false);
validatePasswordEtc()
}}
placeholder="..."
value={password}
onChangeText={handleChangePassword}
/>
)}
If you think for a moment you will find that an alert and a modal are both a kind of pop-up components. And that leads you to create your own pop-up component instead of using ready-made if you don't have it.
return (
<Modal
animationType="slide"
transparent={true}
onBackdropPress={() => console.log('Pressed')}
visible={props.modalVisible}
onRequestClose={ResetValues}>
<View
style={{
position: 'absolute',
bottom: 0,
right: 0,
backgroundColor: '#4D4D4D',
width: (windowWidth * 100) / 100,
height: (windowHeight * 100) / 100,
}}>
!!!!!!!!! your elements here like text,input,buttons and etc....!!!!!
</View>
</Modal>
);

How to use dynamic style class in React Native

I am getting the style class from Rest Web Service.
try {
var securityTokenInBean = {
securityToken: authToken
};
fetchPost(
"monitorprobe/getAllMonitoringProbe",
"POST",
securityTokenInBean,
json => {
this.setState({
isLoading: false,
sumUp: json.sumUp,
styleClass : json.styleClass
});
this.state.isLoading = false;
},
err => {
console.log("needToCallBack: api call failed." + err);
//error(this.props.navigation,'error in needToCallBack ws call');
}
);
} catch (error) {
console.log("needToCallBack: api call failed." + error);
}
I need to use the style class in my View component. The value of styleClass is either criticalProbe,issueProbe,warningProbe,expiredProbe or okProbe
I have defined the styles for the all the classed defined in my StyleSheet.
const styles = StyleSheet.create({
criticalProbe : {
backgroundColor: 'black',
},
issueProbe : {
backgroundColor: 'red',
},
warningProbe : {
backgroundColor: 'orange',
},
expiredProbe : {
backgroundColor: 'yellow',
},
okProbe : {
backgroundColor: 'green',
}
});
How do I use the styleClass in my View Component which comes from rest service as the style class is Dynamic?
I tried with
const criticalProbeStyleClass = styleClass.criticalProbeStyleClass;
console.log(criticalProbeStyleClass);//comes as okProbe
<View style={[styles.box, styles.criticalProbeStyleClass ]}>
<Text style={styles.title}>Critical</Text>
<Text style={styles.criticalProbeStyleClass}>{sumUp.totalCriticalProbe}</Text>
</View>
But it does not work.
To verify I have tried with by hard coding style class and looks fine
<View style={[styles.box, styles.okProbe]}>
<Text style={styles.title}>Critical</Text>
<Text style={styles.criticalProbeStyleClass}>{sumUp.totalCriticalProbe}</Text>
</View>
If your request returning just a name for the style property;
Create a file including all your styling that you want (globalStyles.js for example) and export it. In the component you want to use import it. Then you can use the file shown like below.
const styles = StyleSheet.create({
criticalProbe : {
backgroundColor: 'black',
},
issueProbe : {
backgroundColor: 'red',
},
warningProbe : {
backgroundColor: 'orange',
},
expiredProbe : {
backgroundColor: 'yellow',
},
okProbe : {
backgroundColor: 'green',
}
});
export default styleClasses;
<View style={[styles.box, styleClasses[styleClass.criticalProbeStyleClass] ]}>
<Text style={styles.title}>Critical</Text>
<Text style={styles.criticalProbeStyleClass}>{sumUp.totalCriticalProbe}</Text>
</View>

how to design react native OTP enter screen?

I am new in react native design .Let me know how to achieve the screen shown below
is it necessary to use 4 TextInput or possible with one?
You can use just one hidden TextInput element and attach an onChangeText function and fill values entered in a Text view (you can use four different text view of design requires it).
Make sure to focus the TextInput on click of Text view if user click on it
Here I have created a screen with Six text input for otp verfication with Resend OTP functionality with counter timer of 90 sec. Fully tested on both android and ios.
I have used react-native-confirmation-code-field for underlined text input.
Below is the complete code.
import React, { useState, useEffect } from 'react';
import { SafeAreaView, Text, View ,TouchableOpacity} from 'react-native';
import { CodeField, Cursor, useBlurOnFulfill, useClearByFocusCell } from
'react-native-confirmation-code-field';
import { Button } from '../../../components';
import { styles } from './style';
interface VerifyCodeProps {
}
const CELL_COUNT = 6;
const RESEND_OTP_TIME_LIMIT = 90;
export const VerifyCode: React.FC<VerifyCodeProps> = () => {
let resendOtpTimerInterval: any;
const [resendButtonDisabledTime, setResendButtonDisabledTime] = useState(
RESEND_OTP_TIME_LIMIT,
);
//to start resent otp option
const startResendOtpTimer = () => {
if (resendOtpTimerInterval) {
clearInterval(resendOtpTimerInterval);
}
resendOtpTimerInterval = setInterval(() => {
if (resendButtonDisabledTime <= 0) {
clearInterval(resendOtpTimerInterval);
} else {
setResendButtonDisabledTime(resendButtonDisabledTime - 1);
}
}, 1000);
};
//on click of resend button
const onResendOtpButtonPress = () => {
//clear input field
setValue('')
setResendButtonDisabledTime(RESEND_OTP_TIME_LIMIT);
startResendOtpTimer();
// resend OTP Api call
// todo
console.log('todo: Resend OTP');
};
//declarations for input field
const [value, setValue] = useState('');
const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT });
const [props, getCellOnLayoutHandler] = useClearByFocusCell({
value,
setValue,
});
//start timer on screen on launch
useEffect(() => {
startResendOtpTimer();
return () => {
if (resendOtpTimerInterval) {
clearInterval(resendOtpTimerInterval);
}
};
}, [resendButtonDisabledTime]);
return (
<SafeAreaView style={styles.root}>
<Text style={styles.title}>Verify the Authorisation Code</Text>
<Text style={styles.subTitle}>Sent to 7687653902</Text>
<CodeField
ref={ref}
{...props}
value={value}
onChangeText={setValue}
cellCount={CELL_COUNT}
rootStyle={styles.codeFieldRoot}
keyboardType="number-pad"
textContentType="oneTimeCode"
renderCell={({ index, symbol, isFocused }) => (
<View
onLayout={getCellOnLayoutHandler(index)}
key={index}
style={[styles.cellRoot, isFocused && styles.focusCell]}>
<Text style={styles.cellText}>
{symbol || (isFocused ? <Cursor /> : null)}
</Text>
</View>
)}
/>
{/* View for resend otp */}
{resendButtonDisabledTime > 0 ? (
<Text style={styles.resendCodeText}>Resend Authorisation Code in {resendButtonDisabledTime} sec</Text>
) : (
<TouchableOpacity
onPress={onResendOtpButtonPress}>
<View style={styles.resendCodeContainer}>
<Text style={styles.resendCode} > Resend Authorisation Code</Text>
<Text style={{ marginTop: 40 }}> in {resendButtonDisabledTime} sec</Text>
</View>
</TouchableOpacity >
)
}
<View style={styles.button}>
<Button buttonTitle="Submit"
onClick={() =>
console.log("otp is ", value)
} />
</View>
</SafeAreaView >
);
}
Style file for this screen is in given below code:
import { StyleSheet } from 'react-native';
import { Color } from '../../../constants';
export const styles = StyleSheet.create({
root: {
flex: 1,
padding: 20,
alignContent: 'center',
justifyContent: 'center'
},
title: {
textAlign: 'left',
fontSize: 20,
marginStart: 20,
fontWeight:'bold'
},
subTitle: {
textAlign: 'left',
fontSize: 16,
marginStart: 20,
marginTop: 10
},
codeFieldRoot: {
marginTop: 40,
width: '90%',
marginLeft: 20,
marginRight: 20,
},
cellRoot: {
width: 40,
height: 40,
justifyContent: 'center',
alignItems: 'center',
borderBottomColor: '#ccc',
borderBottomWidth: 1,
},
cellText: {
color: '#000',
fontSize: 28,
textAlign: 'center',
},
focusCell: {
borderBottomColor: '#007AFF',
borderBottomWidth: 2,
},
button: {
marginTop: 20
},
resendCode: {
color: Color.BLUE,
marginStart: 20,
marginTop: 40,
},
resendCodeText: {
marginStart: 20,
marginTop: 40,
},
resendCodeContainer: {
flexDirection: 'row',
alignItems: 'center'
}
})
Hope it will be helpful for many. Happy Coding!!
I solved this problem for 6 digit otp by Following Chethan's answer.
Firstly create a array 'otp' initialised with otp = ['-','-','-','-','-','-'] in state,then create a otpVal string in state like this
const [otp, setOtp] = useState(['-', '-', '-', '-', '-', '-']);
const [otpVal, setOtpVal] = useState('');
Now the actual logic of rendering otp boxes willbe as follows.
<TextInput
onChangeText={value => {
if (isNaN(value)) {
return;
}
if (value.length > 6) {
return;
}
let val =
value + '------'.substr(0, 6 - value.length);
let a = [...val];
setOtpVal(a);
setOtp(value);
}}
style={{ height: 0 }}
autoFocus = {true}
/>
<View style={styles.otpBoxesContainer}>
{[0, 1, 2, 3, 4, 5].map((item, index) => (
<Text style={styles.otpBox} key={index}>
{otp[item]}
</Text>
))}
</View>
with styles of otpBoxesContainer and otpBox as below:
otpBoxesContainer: {
flexDirection: 'row'
},
otpBox: {
padding: 10,
marginRight: 10,
borderWidth: 1,
borderColor: lightGrey,
height: 45,
width: 45,
textAlign: 'center'
}
Now , since height of TextInput is set to 0, it doesn't show up to the user but it still takes the input. And we modify and store that input in such a way, that we can show it like values are entered in separate input boxes.
I was facing the same problem and I managed to develop a nicely working solution. Ignore provider, I am using it for my own purposes, just to setup form values.
Behavior:
User enters first pin number
Next input is focused
User deletes a number
Number is deleted
Previous input is focused
Code
// Dump function to print standard Input field. Mine is a little customised in
// this example, but it does not affects the logics
const CodeInput = ({name, reference, placeholder, ...props}) => (
<Input
keyboardType="number-pad"
maxLength={1}
name={name}
placeholder={placeholder}
reference={reference}
textAlign="center"
verificationCode
{...props}
/>
);
// Logics of jumping between inputs is here below. Ignore context providers it's for my own purpose.
const CodeInputGroup = ({pins}) => {
const {setFieldTouched, setFieldValue, response} = useContext(FormContext);
const references = useRef([]);
references.current = pins.map(
(ref, index) => (references.current[index] = createRef()),
);
useEffect(() => {
console.log(references.current);
references.current[0].current.focus();
}, []);
useEffect(() => {
response &&
response.status !== 200 &&
references.current[references.current.length - 1].current.focus();
}, [response]);
return pins.map((v, index) => (
<CodeInput
key={`code${index + 1}`}
name={`code${index + 1}`}
marginLeft={index !== 0 && `${moderateScale(24)}px`}
onChangeText={(val) => {
setFieldTouched(`code${index + 1}`, true, false);
setFieldValue(`code${index + 1}`, val);
console.log(typeof val);
index < 3 &&
val !== '' &&
references.current[index + 1].current.focus();
}}
onKeyPress={
index > 0 &&
(({nativeEvent}) => {
if (nativeEvent.key === 'Backspace') {
const input = references.current[index - 1].current;
input.focus();
}
})
}
placeholder={`${index + 1}`}
reference={references.current[index]}
/>
));
};
// Component caller
const CodeConfirmation = ({params, navigation, response, setResponse}) => {
return (
<FormContext.Provider
value={{
handleBlur,
handleSubmit,
isSubmitting,
response,
setFieldTouched,
setFieldValue,
values,
}}>
<CodeInputGroup pins={[1, 2, 3, 4]} />
</FormContext.Provider>
);
};
try this package https://github.com/Twotalltotems/react-native-otp-input
it works best with both the platforms
try this npm package >>> react-native OTP/Confirmation fields
below is the screenshot of the options available, yours fall under underline example.
below is the code for underline example.
import React, {useState} from 'react';
import {SafeAreaView, Text, View} from 'react-native';
import {
CodeField,
Cursor,
useBlurOnFulfill,
useClearByFocusCell,
} from 'react-native-confirmation-code-field';
const CELL_COUNT = 4;
const UnderlineExample = () => {
const [value, setValue] = useState('');
const ref = useBlurOnFulfill({value, cellCount: CELL_COUNT});
const [props, getCellOnLayoutHandler] = useClearByFocusCell({
value,
setValue,
});
return (
<SafeAreaView style={styles.root}>
<Text style={styles.title}>Underline example</Text>
<CodeField
ref={ref}
{...props}
value={value}
onChangeText={setValue}
cellCount={CELL_COUNT}
rootStyle={styles.codeFieldRoot}
keyboardType="number-pad"
textContentType="oneTimeCode"
renderCell={({index, symbol, isFocused}) => (
<View
// Make sure that you pass onLayout={getCellOnLayoutHandler(index)} prop to root component of "Cell"
onLayout={getCellOnLayoutHandler(index)}
key={index}
style={[styles.cellRoot, isFocused && styles.focusCell]}>
<Text style={styles.cellText}>
{symbol || (isFocused ? <Cursor /> : null)}
</Text>
</View>
)}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
root: {padding: 20, minHeight: 300},
title: {textAlign: 'center', fontSize: 30},
codeFieldRoot: {
marginTop: 20,
width: 280,
marginLeft: 'auto',
marginRight: 'auto',
},
cellRoot: {
width: 60,
height: 60,
justifyContent: 'center',
alignItems: 'center',
borderBottomColor: '#ccc',
borderBottomWidth: 1,
},
cellText: {
color: '#000',
fontSize: 36,
textAlign: 'center',
},
focusCell: {
borderBottomColor: '#007AFF',
borderBottomWidth: 2,
},
})
export default UnderlineExample;
source : Github Link to above Code
Hope it helps! :)
There is a plugin React Native Phone Verification works both with iOS and Android (Cross-platform) with this you can use verification code picker matching with your requirement.
We used to do it with single hidden input field as described in #Chethan’s answer. Now since RN already supports callback on back button on Android platform (since RN 0.58 or even before). It is possible to do this with just normal layout of a group of text inputs. But we also need to consider the text input suggestion on iOS or auto fill on Android. Actually, we have develop a library to handle this. Here is blog to introduce the library and how to use it. And the source code is here.
#kd12345 : You can do it here in:
onChangeText={(val) => {
setFieldTouched(`code${index + 1}`, true, false);
setFieldValue(`code${index + 1}`, val);
console.log(typeof val);
// LITTLE MODIFICATION HERE
if(index < 3 && val !== '') {
references.current[index + 1].current.focus();
// DO WHATEVER
}
}}