How to create global helper function in react native?

global variable

class MainActivity extends Component {

  constructor(){
     super();

     // Creating Global Variable.
     global.SampleVar = 'This is Global Variable.';
  }
}

in second activity

class SecondActivity extends Component {

  render(){
    return(
       <View>
          <Text> {global.SampleVar} </Text>
       </View>
   );
  }
}

But if you want to have a global function

export function TestFunc1() {

}

export function TestFunc2() {

}

Then import and use

import { TestFunc1 } from './path_to_file'

The way we've done it in the past:

  1. Create a file that exports a function:

    module.exports = function(variable) {    
       console.log(variable);
    }
    
  2. Require the file when you want to use it, in a variable:

    var func = require('./pathtofile');
    
  3. Use function:

    func('myvariable');
    

Tags:

React Native