Search code examples
javascriptfunctionreact-nativemasktextinput

How to make TextInput prefill in React Native app?


I have a TextInput component in my React Native app. And i need to make the field is pre-populated with a mask of 408xx810xxx, 1-3 and 6-8 digits in the field, their change is prohibited to put for users. Can somebody recommend the best way how can i do it?

          <TextInput
            style={[SS.input, styles.input]}
            placeholder={props.placeholder} placeholderTextColor={theme.inputPlaceholder}
            underlineColorAndroid='transparent' editable={!props.disabled}
            keyboardType={props.keyboardType || 'default'} autoCapitalize={capitalize}
            keyboardAppearance={props.keyboardAppearance}
            autoCorrect={autoCorrect} selection={state.position}
            secureTextEntry={this.state.guarded}
            value={this.state.value}
            onChangeText={this._onChangeText}
            onFocus={this._onFocus} onBlur={this._onBlur}
            autoFocus={props.autoFocus}
            multiline={props.multiline}
            maxLength={props.maxLength}
            onContentSizeChange={onContentSizeChange}
          />

Solution

  • For pre-population, you can assign hardcoded masked value to the state this.state.value in your constructor.

    And for masking I recommend you using this library:

    https://github.com/react-native-community/react-native-text-input-mask

    using this library masking work something like this

    <TextInputMask
      refInput={ref => { this.input = ref }}
      onChangeText={(formatted, extracted) => {
      console.log(formatted) // +1 (123) 456-78-90
      console.log(extracted) // 1234567890
     }}
      mask={"+1 ([000]) [000] [00] [00]"}
    

    />