Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextInput allow only numbers react native

I'm using TextInput to allow only numbers using state, it works on android but not on iOS. Here's how I'm using state to allow only numbers.

handleInputChange = (text) => {

  if (/^\d+$/.test(text) || text === '') {
    this.setState({
      text: text
    });
  }
}

my render method

render = () => {
  return (
    <View style={{
      flex: 0,
      flexDirection: 'row',
        alignItems: 'flex-end',
        marginTop: 50
    }}>
      <View style={{ flex: 0, marginLeft: 10 }}>
        <Text style={{ fontSize: 20}}>$</Text>
      </View>
      <View style={{flex: 1,}}>
        <TextInput
          onChangeText={this.handleInputChange}
          value={this.state.text}
          underlineColorAndroid='transparent'
          autoCorrect={false}
          spellCheck={false}
          style={{ paddingLeft: 5, fontSize: 20 }} />
      </View>
    </View>
  );
}

enter image description here

This only works in Android, I guess because the state has changed react doesn't update the ui.

like image 597
Junius L. Avatar asked Jan 27 '23 11:01

Junius L.


2 Answers

pls try this:

  1. keyboardType='numeric' in the tag TextInput
  2. when you prove don't put the numbers with the keyboard of your pc, pls use the keyboard of the emulator
  3. if still not working put this textContentType='telephoneNumber'
like image 127
Pedro Rico Avatar answered Jan 31 '23 17:01

Pedro Rico


As Ravi Rupareliya said this's a bug, which TextInput doesn't update, when the state text is shorter than the current TextInput value. Seems like the bug has been fixed in react-native 0.57.RC. For now I'm using the following fix.

handleInputChange = (text) => {

    const filteredText = text.replace(/\D/gm, '');

    if(filteredText !== text) {
      // set state text to the current TextInput value, to trigger
      // TextInput update.
      this.setState({ text: text });

      // buys us some time until the above setState finish execution
      setTimeout(() => {

        this.setState((previousState) => {
          return {
            ...previousState,
            text: previousState.text.replace(/\D/gm, '')
          };
        });

      }, 0);
    } else {
      this.setState({ text: filteredText });
    }
}

enter image description here

like image 24
Junius L. Avatar answered Jan 31 '23 16:01

Junius L.