Efosa
Efosa

Reputation: 137

React Native TextInput does not display number type value

I have a pre-rendered value that always has to be a number type. I set the TextInput value to this number but it does not display in the input field unless I convert the number to a string. However, when the number is converted to a string using toString() or String(value), editing the TextInput by clearing out the field causes NaN to display in the field which becomes impossible to wipe out as it keeps recurring after every attempt.

Here is how the TextInput looks:

<TextInput value={5}/> 
//displays nothing in the field unless when like this: 

<TextInput value="5"/>

<TextInput value={value.toString()}/>  and <TextInput value={String(value}/> cause NaN when the field is cleared completely

It also does not emit a number value, but not rendering a number value is the more serious problem.

Please can anyone tell me how I can solve this?

Upvotes: 0

Views: 4152

Answers (2)

polcats
polcats

Reputation: 154

You could simplify this by using string literals.

You have

const [num, setNum] = React.useState(0);

And then,

<TextInput 
   keyboardType="numeric" 
   onChangeText={(newNum) => setNum(newNum)} 
   defaultValue={`${num}`} />

Upvotes: 4

Muhammad Iqbal
Muhammad Iqbal

Reputation: 1495

not rendering a number value is the more serious problem.

TextInput's value prop type is string ,that's why you must explicitly convert it while passing it as prop to your TextInput.

for more info

you can achieve this by using state and onTextChange method check code snippet.

import * as React from 'react';
import { Text, View, StyleSheet ,TextInput} from 'react-native';
import Constants from 'expo-constants';


export default function App() {
  const [numValue,setNumValue] = React.useState(9991122)
  return (
    <View style={styles.container}>
      <TextInput value={numValue.toString()} keyboardType={'numeric'} style={{margin:100,borderWidth:2}} onChangeText={(e)=>setNumValue(e)}/> 
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
 
});

Upvotes: 2

Related Questions