14

How can I create Global Helper functions in react-native?

I would like to use for accessing sqlite database or fetching data from server. Can I create a JavaScript file with functions and call that functions from multiple views?

gran33
  • 12,421
  • 9
  • 48
  • 76
Phyo
  • 692
  • 1
  • 5
  • 14

5 Answers5

21

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');
    
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
Nader Dabit
  • 52,483
  • 13
  • 107
  • 91
5

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'
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
3

2 methods, not sure which one is better:

  1. Method

Use:

window.foo = function(val) {
   alert(val);
}
  1. (Not really global) Inside your class where you export and require in the need-to-use file, you can define your function.

See this:

var React = require('react-native');

var {
  View,
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

var MoviesScreen = React.createClass({
  foo : function(val) {
    alert(val);
  },

render: function() {
    return (
      <View style={styles.container}>      
      </View>
    );
  },
});


module.exports = MoviesScreen;
c-chavez
  • 7,237
  • 5
  • 35
  • 49
gran33
  • 12,421
  • 9
  • 48
  • 76
3

I have this helper function:

function myfunction(foo)

I declare it globally as:

global.myfunction = function myfunction(foo) {...};
c-chavez
  • 7,237
  • 5
  • 35
  • 49
floatingice
  • 179
  • 6
1

I did in a simple way like this:

  1. I created a helpers.js file that will contain all the helper functions for my project & placed it like this: ./src/helpers.js(you can place anywhere you like).

  2. Exported the function like this from helpers.js:

    export function GlobalLogout(str) {.....}

  3. Then I imported the function like this:

    import { GlobalLogout } from '../src/helpers';

  4. And finally use the function in the file like this:

    GlobalLogout(data);

Hope this helps anyone!