04-Apr-2023
.
Admin
Hi Guys,
If you need to see example of react native TextInput accepts only numbers. you will learn react native input number only. I would like to show you TextInput allow only numbers in react native. you can understand a concept of how to TextInput accept only numbers in react native. Let's get started with how to only allow for numbers on TextInput in react native.
In this instance TextInput only accepts numbers, a warning message is shown after you enter Except a numeric value.
Step 1: Download Project
In the first step run the following command to create a project.
expo init ExampleApp
Step 2: App.js
In this step, You will open the App.js file and put the code.
import React from 'react';
import { StyleSheet, View, TextInput, Button, Keyboard, Alert } from 'react-native';
const App = () => {
const [number, setNumber] = React.useState('');
const onChanged = (text) => {
let newText = '';
let numbers = '0123456789';
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
else {
alert("please enter numbers only");
}
}
setNumber(newText);
}
const onPress = () => {
if (number.length !== 0) {
Alert.alert(
"Confirm Number",
number,
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
},
{
text: "OK",
onPress: () => console.log("OK Pressed"),
},
],
);
setNumber('');
Keyboard.dismiss();
}
}
return (
<View style={styles.container}>
<TextInput
keyboardType='numeric'
onChangeText={text => onChanged(text)}
value={number}
style={styles.input}
placeholder='Number'
maxLength={10}
/>
<View style={styles.buttonContainer}>
<Button
title='submit'
onPress={() => onPress()}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent:'center',
alignItems:'center',
},
input: {
borderWidth:1,
width:'80%',
borderColor:'#c7c3c3',
padding:10,
},
buttonContainer: {
marginTop:10,
width:'80%',
},
})
export default App;
Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output :
It will help you...
#React Native