Phyo
Phyo

Reputation: 692

How to create global helper function in react native?

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?

Upvotes: 14

Views: 26417

Answers (5)

Nader Dabit
Nader Dabit

Reputation: 53711

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');
    

Upvotes: 21

Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18883

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'

Upvotes: 5

Aqeeb Imtiaz Harun
Aqeeb Imtiaz Harun

Reputation: 167

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!

Upvotes: 1

gran33
gran33

Reputation: 12991

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;

Upvotes: 3

floatingice
floatingice

Reputation: 189

I have this helper function:

function myfunction(foo)

I declare it globally as:

global.myfunction = function myfunction(foo) {...};

Upvotes: 3

Related Questions