Search code examples
classcontrollerreact-nativerequire

React-Native require a class from a 'non-class' .js and use the functions


I want to "outsource" my logical functions which I need over more than 3-4 classes. Therefore I created a .js file and entered the functions. But I did not create a class for it. Instead I am using the following syntax:

var myMainClassWithTheFunction = require('./myMain...');

var FunctionHandler = {
    myFunction(){
        myMainClassWiththeFunction.testFunction();            
    }
}

module.exports = FunctionHandler

Inside of this function I want to use the method of another class -> The class is structured like the following

class MyMainClass.. extends Component {
    constructor(props){
        super(props);
    }
static testFunction(
    alert("Test");
)
render(){...}
}

module.exports = MyMainClass;

The class MyMainClass... is working (Checked through many other calls - But those just got from other classes)

I also tested myFunction from FunctionHandler with a function testAlert() which worked perfectly.

The main issue
As far as I try to call the testFunction() from the MainClass I get the following error:

undefined is not a function(evaluating 'myMainClass.testFunction()'

  • I tried a static/non-static function

My question How can I solve this problem - or do you even know better ways to outsource the logical behavior?


Solution

  • After hours of searching what my issue is here i found out that:

    If you fill your js-file with just a var like i did. You cannot require other classes in another var and use the var in other var's (in my case my FunctionHandler var)

    Solution

    I required the classes inside my var so i could use them.

    var FunctionHandler = {
        var myMainClassWithTheFunction = require('./myMain...');
    
        myFunction(){
            myMainClassWiththeFunction.testFunction();            
        }
    }
    

    module.exports = FunctionHandler

    I am sure many people now roll their eyes if they read this and think 'this is clear' but for me it was a timeintensive issue. Hopefully anyone can help this