Home > Blockchain >  Showing undefined when I press any number button in my Calculator App, showing the same in Console a
Showing undefined when I press any number button in my Calculator App, showing the same in Console a

Time:11-11

I'm new to react native and still a beginner, I was following a youtube video on react native where he was building a calculator app. For him it was working and the numbers were showing.

text is the parameter given to the buttonPressed function and it should display in the console.log(text)

constructor() {
   super();
   this.state = {
    resultText: ""
   }
}
buttonPressed(text) {
   console.log(text)
   this.setState({
    resultText: this.state.resultText text
   })
}
 render() {
  let rows = []
  let nums = [[1,2,3], [4,5,6], [7,8,9], ['.',0,'=']]
   for(let i=0; i<4; i  ) {
     let row= []
     for(j=0; j<3; j  ) {
      row.push(<TouchableOpacity onPress={() => this.buttonPressed(nums[i][j])} style={styles.btn}>
        <Text style={styles.txt}>{nums[i][j]}</Text>
      </TouchableOpacity>)
     }
     rows.push(<View style={styles.row}>{row}</View>)
    }

   let operations = ['D',' ', '-', '*', '/']
   let ops = []
    for(let i=0; i<4; i  ) {
     ops.push(<TouchableOpacity style={styles.btn}>
      <Text style={styles.txt}>{operations[i]}</Text>
      </TouchableOpacity>)
    }

   return (
      <View style={styles.Container}>
        <View style={styles.result}>
          <Text style={styles.resultText}>{this.state.resultText}</Text>
        </View>
        <View style={styles.calculations}>
          <Text style={styles.txt}>121</Text>
        </View>
        <View style={styles.buttons}>
          <View style={styles.numbers}>
              {rows}
          </View>
          <View style={styles.operations}>
              {ops}
          </View>
        </View>
      </View>
    );
  }
}

It should have shown the numbers pressed but instead it was just showing undefined on the result section of the app and even on the console.

CodePudding user response:

I think you missed a variable declaration inside for loop here , j= 0 should be let j=0

for(let j=0; j<3; j  ) {
      row.push(<TouchableOpacity onPress={() => this.buttonPressed(nums[i][j])} style={styles.btn}>
        <Text style={styles.txt}>{nums[i][j]}</Text>
      </TouchableOpacity>)
     }
  • Related