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.
JavaScript
x
37
37
1
import React from "react";
2
import { StyleSheet, Text, View } from "react-native";
3
import { Button } from "react-native-elements";
4
5
export default class App extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
counter: 0
10
};
11
}
12
13
increment() {
14
this.setState({ counter: (counter += 1) });
15
}
16
17
render() {
18
return (
19
<View style={styles.container}>
20
<Text>Open up App.js to start working on your app!</Text>
21
<Text>{this.state.counter}</Text>
22
<Button title="Press Me" onPress={this.increment}></Button>
23
</View>
24
);
25
}
26
}
27
28
const styles = StyleSheet.create({
29
container: {
30
flex: 1,
31
backgroundColor: "#fff",
32
alignItems: "center",
33
justifyContent: "center"
34
}
35
});
36
37
Advertisement
Answer
Change your increment
function to
JavaScript
1
6
1
increment = () => {
2
this.setState({
3
counter: this.state.counter + 1
4
});
5
}
6
Make sure to define your increment
function as an arrow function otherwise you can’t access it from Button
.
JavaScript
1
2
1
<Button title="Press Me" onPress={this.increment}></Button>
2
Feel free for doubts.