Skip to content
Advertisement

Can’t find variable: counter, in expo

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

Advertisement

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement