Skip to content

Instantly share code, notes, and snippets.

@AlexisLeon
Created January 15, 2017 04:28
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexisLeon/80b5641eb30b43bc598288e41052ac39 to your computer and use it in GitHub Desktop.
Save AlexisLeon/80b5641eb30b43bc598288e41052ac39 to your computer and use it in GitHub Desktop.
TextInput accepts only numbers - React Native
import React, { Component } from 'react';
import { TextInput } from 'react-native';
class Input extends Component {
constructor(props) {
super(props);
this.state = {
text: ''
};
}
handleInputChange = (text) => {
if (/^\d+$/.test(text)) {
this.setState({
text: text
});
}
}
render () {
return (
<TextInput
keyboardType='numeric'
onChangeText={this.handleInputChange}
value={this.state.text}
/>
)
}
}
@moeabdol
Copy link

Thanks...this is great!

@gate3
Copy link

gate3 commented Jun 9, 2019

Nice snippet, I tried the code and discovered a bug though. You can't set the text back to blank. Here is how i changed the code

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

@AmeerHamzaRiaz
Copy link

thanks

@hsandrade
Copy link

thanks!
and @gate3 too for updated code

@HVHMobileDeveloper
Copy link

Thanks

@azatTemirbek
Copy link

what about
-5
.2
0.5
-0.5

@JindalSaw
Copy link

It ain't working!!!

@ciela0426
Copy link

It's working! Thx!

@naojamg
Copy link

naojamg commented Mar 9, 2021

Nice snippet, I tried the code and discovered a bug though. You can't set the text back to blank. Here is how i changed the code

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

this works great!!!

@mastercode15
Copy link

Nice snippet, I tried the code and discovered a bug though. You can't set the text back to blank. Here is how i changed the code

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

Great, this works excellent

@Owusu-Wilson
Copy link

Thanks
This was very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment