1

Story:

I am trying to create a credit card input text field. The goal is to include spaces after every 4th, 8th and 12th character.

Expected result:

The cursor should remain at the end of the textInput after the adding of spaces has occured

Actual result:

On the windows platform, the cursor doesn't continue at the end of the textInput but is instead, behind the space and the last number typed.

PS.

To make this clearer, I have a small repo reproducing the problem which can be found here https://github.com/meddyrainzo/maskedTextInput/tree/master

Relevant code blocks from the repo

imports used (aside from the usual stuff from react and react-native)
import valid from 'card-validator';
The render method
render() {
  const { creditCardNumber } = this.state;
  const { container } = styles;
  return (
    <View style={container}>
      <TextInput
        placeholder='Enter text' 
        value={creditCardNumber}
        onChangeText={inputValue => this.onChangeTextHandler(inputValue)}
      />
    </View>
  );
}
The onChangeTextHandler method
onChangeTextHandler = (textInput) => {
  const card = valid.number(textInput).card || fallbackCard;    
  const maxCardLength = card.lengths[card.lengths.length -1];

  const onlyNumericValues = this.removeNonNumber(textInput);
  const cardNumberWithoutGaps = onlyNumericValues.substr(0, maxCardLength);
  const creditCardNumber = this.addGaps(cardNumberWithoutGaps);
  this.setState({creditCardNumber});
}
The removeNonNumber method
removeNonNumber = (string = '') => string.replace(/[^\d]/g, '');

Finally, the addGaps method which is where the spaces are added

addGaps = (str) => {
  const gaps = [0, 4, 8, 12];
  const offsets = (gaps).concat([str.length]);

  return offsets.map((end, index) => {
    if (index === 0) return '';
    const start = offsets[index - 1];
    return str.substr(start, end - start);
  }).filter(part => part !== '').join(' ');
};

All codeblocks above are in the App.js file in the repo link. I will still recommend cloning the repo so you can manually test and see how the results differ in iOS and Android vs Windows (for those interested).

So my main question is, does anyone know how to move the cursor to the end of the textInput on Windows? I know react-native added a prop to the textInput called "selection" which you can use to control the cursors start and end position but checking the react-native code for windows, there doesn't seem to be an implementation for selection prop yet.

Versions used:

react-native: 0.49.3

MRainzo
  • 3,800
  • 2
  • 16
  • 25
  • 1
    Well formed question. But you could still try to put the relevant pieces of code in to the question to make answering easier? – pirho Nov 14 '17 at 09:49
  • @pirho Thanks for your comment. I will update the question with relevant pieces of code from the repo – MRainzo Nov 14 '17 at 09:50

0 Answers0