React Native giving error that variable is not defined when it is

Tags: , ,



I have linked an external JS File using require(), it has even recognized it. When i will call a function from that external file it will indicate that the function been recognized but it will still give error that it Can’t find the variable (in my case is a function named text()). My App.js:

require('./comp/functions.js')
import React from 'react'
import {View, Text, StyleSheet, Button} from 'react-native'


export default function App() {
      return(<>
      <View style={styles.loginbox}>
        <Text style={{textAlign: "center", fontWeight: "bold", fontSize: 30}}>LOGIN</Text>
        <Button title="Login Now!" onPress={test}/>

      </View>
      </>)
}

const styles = StyleSheet.create({
   loginbox: {
     position: "relative",
     top: 100
   }
})

functions.js:

function test() {
    alert(123)
  }

I want it to run the test() function when the Login Now! button has been pressed

Answer

You need to export your functions from your functions.js first. And then, you can import it into your app. The following should work.

functions.js

export default function test() {
  alert(123);
}

app.js

import test from "./functions";
import React from "react";
import { View, Text, StyleSheet, Button } from "react-native";

export default function App() {
  return (
    <>
      <View style={styles.loginbox}>
        <Text style={{ textAlign: "center", fontWeight: "bold", fontSize: 30 }}>
          LOGIN
        </Text>
        <Button title="Login Now!" onPress={test} />
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  loginbox: {
    position: "relative",
    top: 100
  }
});


Source: stackoverflow