2

I am trying to build an input field which will only take numbers as input. Minimal component definition to explain my problem is as below

type Props = {};
export default class App extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      text: 'PlaceHolder'
    }
  }

  sanitizeInput(input) {
    let sanitizedInput = input.replace(/[^0-9]/g, '');
    this.setState({text: sanitizedInput});
  }

  render() {
    console.log("In render - ", this.state.text);
    return (
      <View style={{flex: 1, justifyContent: 'center'}}>
        <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.sanitizeInput(text)}
        value={this.state.text}
      />
      </View>
    );
  }
}

But, when I am executing it, I am not getting the desired result. It seems that the TextInput is not respecting the value prop passed into it. The console.log is clearly showing desired value to be shown in TextInput, but I am not able to get that value properly in TextInput of device.

A video describing my problem is posted here

Abhishek
  • 2,543
  • 4
  • 34
  • 46
  • And changing the `keyboardType` to `numeric` does not solve your problem? – parohy Mar 19 '18 at 11:31
  • Which version of react-native are you using? I have tested your code on RN-52, it works as expected. – Prasun Mar 19 '18 at 12:34
  • @PrasunPal It's latest one. 0.54.2. I will spin up the code on RN-52 and post with my findings. – Abhishek Mar 19 '18 at 12:49
  • @parohy That problem can be solved by setting keyboardType to numeric, but this is just a minimalistic demonstration of the problem. I also have to format certain inputs by user, as formatting currency, sanitising text inputs, which I can not do unless this thing works as expected. – Abhishek Mar 19 '18 at 12:50
  • @PrasunPal - You are right. It is indeed working with 0.52.0. This is a clear regression then. But there is a visible flicker in iOs which gets worse on Android. Can you please confirm that! Thanks. – Abhishek Mar 19 '18 at 13:04
  • Yes, I am also experiencing the behavior in RN-54 as you have specified here. I think there might be an issue with TextInput update, as both the values between 2 consecutive (number and character) input are same. like 123 -> 123x -> regEx(123x) -> 123. – Prasun Mar 19 '18 at 13:17

0 Answers0