Home > database >  The output of TextInput is undefined in React Native
The output of TextInput is undefined in React Native

Time:11-02

I'm currently creating a simple calculator in React Native and I don't know where is the problem in my code. There's no error but the output was always undefined whenever I put some numbers on TextInput and click the button.

Here's my code:

    export default class calculator extends Component {
  state = {
    firstNumber: "",
    secondNumber: "",
    operator: "",
    result: "",
  };

  computation() {
    if (this.operator === " ") {
      return (this.state.result = firstNumber   secondNumber);
    } else if (this.operator === "-") {
      return (this.state.result = firstNumber - secondNumber);
    } else if (this.operator === "*") {
      return (this.state.result = firstNumber * secondNumber);
    } else if (this.operator === "/") {
      return (this.state.result = firstNumber / secondNumber);
    } else {
      return (this.state.result = "Not a number!");
    }
  }



  render() {
    return (
      <View>
        <Text>First number</Text>
        <TextInput
          style={styles.input}
          onChangeText={(val) => {
            this.setState({ firstNumber: val });
          }}
        />

        <Text>Operation</Text>
        <TextInput
          style={styles.input}
          onChangeText={(val) => {
            this.setState({ operator: val });
          }}
        />

        <Text>Second number</Text>
        <TextInput
          style={styles.input}
          onChangeText={(val) => {
            this.setState({ secondNumber: val });
          }}
        />

        <Button
          title="="
          onPress={() => {
            this.setState({ result: this.computation });
          }}
        />

        <Text>Output: {this.state.result}</Text>

        <Text>History:</Text>

        
      </View>
    );
  }
}

So I'm using a class component, and I think that I'm not using properly the useState here.

CodePudding user response:

You've forgotten to pass the value props to the TextInput element:

The value to show for the text input. TextInput is a controlled component, which means the native value will be forced to match this value prop if provided

So, pass the related state object values into TextInput:

// rest of the codes ...

<TextInput
  style={styles.input}
  value={this.state.firstNumber}     // ----> here
  onChangeText={(val) => {
    this.setState({ firstNumber: val });
  }}
/>

// and so on for the other TextInput field

// rest of the codes ...

CodePudding user response:

You need to make few changes:

You need to initiate the state variable inside the constructor. Use setState to change the values of a state variable.

Here is the working code

  • Related