Search code examples
javascriptreact-nativeuser-interfaceuser-experience

How to create guided user input in React Native?


I would like to create a guided-input user experience using React Native. By that, I mean the following:

  1. User presses TextInput component to search something. The value AND the placeholder is automatically populated with the prefix "ABCDE-"
  2. The user is presented with "numeric" keyboardType . After they enter four numbers, another "-" is automatically added to the search value as such: "ABCDE-1234-"
  3. The user types four more numbers and the final search value looks like so: "ABCDE-1234-5678"

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.


Solution

  • 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;
    

    Test Link