Reputation: 99
I would like to create a guided-input user experience using React Native. By that, I mean the following:
TextInput
component to search something. The value
AND the placeholder
is automatically populated with the prefix "ABCDE-" keyboardType
. After they enter four numbers, another "-" is automatically added to the search value as such: "ABCDE-1234-"The two aspects of this experience I am curious about are populating prefix "ABCDE-" when onPress
, and adding the second dash after n numbers are typed.
Switching between alphabet, alternate characters, and numbers within the same search is quite awkward and cumbersome, and could be simplified this way.
Upvotes: 0
Views: 826
Reputation: 184
for point 1 you can use onFocus
prop of TextInput like this
<TextInput
value={this.state.searchTerm}
style={/* your style*/}
onFocus={()=>{
if(this.state.searchTerm==""){
this.setState({searchTerm:"ABCDE-"})
}
}}
/>
for Point 2 use keyboardType
and onChangeText
prop of TextInput like this
<TextInput
value={this.state.searchTerm}
style={/* your style*/}
keyboardType={"numeric"}
onChangeText={(text)=>{
/*since there 6 characters placed on focus so n character login will be*/
if(this.state.searchTerm.length>6){
if(value.length%5==0){
let temp = this.state.searchTerm+"-"+text[text.length-1]
onChangeText(temp)
} else {
onChangeText(text)
}
}else{
onChangeText(text)
}
}}
onFocus={()=> {
if(this.state.searchTerm==""){
this.setState({searchTerm:"ABCDE-"})
}
}}
/>
Hopefully, you will get an idea from this code how to implement guided user input
Upvotes: 0
Reputation: 2057
I have made a simple example code like this, you could take it a try and change what you want:
import React, { Component } from "react";
import {TextInput } from "react-native";
class App extends Component {
constructor(props) {
super(props);
this.state = { text: '' };
}
onChangeTextHandler(text){
var len = text.length;
if ((len===5 || len===10)&& len>=this.state.text.length){
text = text +"-"
}
if(text.length!==16){
this.setState({text:text})
}
}
render() {
return (
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1,marginTop:20}}
onChangeText={(text) => this.onChangeTextHandler(text)}
value={this.state.text}
placeholder="ABCDE-1234-5678"
/>
);
}
}
export default App;
Upvotes: 2