Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Undefined is not a function - React Native

I created a simple activity where in if you press inside the circular area, the text in it should change accordingly. The app runs well but when I press inside the circular area, I get an error saying "undefined is not a function ( evaluating 'this.setState( {pressing: true});' ) ". Also, the text inside the circular area should be initially set but it is empty. You can see the activity here. The code is also provided below:

import React, { Component } from "react";
import {
  StyleSheet,
  View,
  AppRegistry,
  Text,
  TouchableHighlight
} from "react-native";

class dhrumil extends Component {
  constructor(props) {
    super(props);
    this.state = { pressing: false };
  }
  _inPress() {
    this.setState({ pressing: true });
  }
  _outPress() {
    this.setState({ pressing: false });
  }
  render() {
    return (
      <View style={styles.mainContainer}>
        <TouchableHighlight
          onPressIn={this._inPress}
          onPressOut={this._outPress}
          style={styles.toucher}
        >
          <View style={styles.smallContainer}>
            <Text style={styles.texter}>
              {this.state.pressing ? "EEK" : "PUSH ME"}
            </Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}
var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: "white",
    justifyContent: "center",
    margin: 10,
    alignItems: "center"
  },
  toucher: {
    borderRadius: 100
  },
  smallContainer: {
    backgroundColor: "#ff0000",
    width: 200,
    height: 200,
    borderRadius: 100
  },
  texter: {
    color: "white",
    fontSize: 10,
    fontWeight: "bold"
  }
});

AppRegistry.registerComponent("dhrumil", () => dhrumil);

How can I solve this?

like image 650
Dhrumil Mayur Mehta Avatar asked Jun 08 '17 11:06

Dhrumil Mayur Mehta


2 Answers

The issue is here:

<TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress}  style={styles.toucher}>

You are setting handlers without fixing the context as the current this. So when the functions are called setState is not found as this will be different. Use bind.

<TouchableHighlight onPressIn={this._inPress.bind(this)}
   onPressOut={this._outPress.bind(this)}  style={styles.toucher}>

Or you can also use arrow function:

 <TouchableHighlight onPressIn={() => this._inPress()}
       onPressOut={() => this._outPress()}  style={styles.toucher}>
like image 82
Suraj Rao Avatar answered Oct 20 '22 04:10

Suraj Rao


simply delete node_modules

run npm install

react-native run-android

It's worked for me.

like image 34
James Siva Avatar answered Oct 20 '22 03:10

James Siva