I am Trying to create a React Native TextInput that only accepts numbers but has an initial value of null
. This value then can incremented/decremented by 1. I am having a hard time converting the initial value to null. My thinking is I have to set null to an empty string somehow but not entirely sure how to do so.
Currently I have it if I start the input out with a numeric value everything works, but if I start it out as null, it can't read toString of null. Any help would be appreciated.
export class Measurement extends Component {
state = {
measurement: null
};
updateMeasurement = measurement => {
this.setState({
measurement: +measurement
});
};
decrement = () => {
this.setState({
measurement: this.state.measurement - 1
});
};
increment = () => {
this.setState({
measurement: this.state.measurement + 1
});
};
render() {
const styles = getStyles();
return (
<View style={styles.container}>
<View style={styles.input}>
<TextInput
style={styles.inputText}
onChange={this.updateMeasurement}
keyboardType="numeric"
placeholder="Enter #"
value={this.state.measurement.toString()}
/>
</View>
<View style={styles.buttonWrapper}>
<Button
buttonStyles={styles.decrementButton}
onPress={this.decrement}
textStyles={styles.decrementButtonText}
>
__
</Button>
<Button
buttonStyles={styles.incrementButton}
onPress={this.increment}
textStyles={styles.buttonText}
>
+
</Button>
</View>
</View>
</BaseType>
);
}
}
getMeasurement() {
return this.state.measurement && this.state.measurement.toString();
}
...
<TextInput
style={styles.inputText}
onChange={this.updateMeasurement}
keyboardType='numeric'
placeholder='Enter #'
value={this.getMeasurement()}
/>