0

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>
    );
}
}

1 Answer 1

2
getMeasurement() {
    return this.state.measurement && this.state.measurement.toString();
}

...

<TextInput
    style={styles.inputText}
    onChange={this.updateMeasurement}
    keyboardType='numeric'
    placeholder='Enter #'
    value={this.getMeasurement()}
/>
Sign up to request clarification or add additional context in comments.

1 Comment

This works! Thank you. I also found another way of doing it, but this way may be more readable. The way I found was by doing this: const value = this.state.measurement === null ? '' : measurement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.