Can’t find variable: counter, in expo

Tags: , , ,



Been using React for a bit and wanted to try out native using expo, when I click on a button to increment a counter, I get a ReferenceError on my phone saying “Can’t find variable: counter”, I don’t get any error on the expo gui or in VSCode, very confused.

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Button } from "react-native-elements";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
  }

  increment() {
    this.setState({ counter: (counter += 1) });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>{this.state.counter}</Text>
        <Button title="Press Me" onPress={this.increment}></Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

Answer

Change your increment function to

increment = () => {
    this.setState({
        counter: this.state.counter + 1
    });
}

Make sure to define your increment function as an arrow function otherwise you can’t access it from Button.

<Button title="Press Me" onPress={this.increment}></Button>

Feel free for doubts.



Source: stackoverflow