Reputation: 692
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
Reputation: 53711
The way we've done it in the past:
Create a file that exports a function:
module.exports = function(variable) {
console.log(variable);
}
Require the file when you want to use it, in a variable:
var func = require('./pathtofile');
Use function:
func('myvariable');
Upvotes: 21
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
Reputation: 167
I did in a simple way like this:
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).
Exported the function like this from helpers.js
:
export function GlobalLogout(str) {.....}
Then I imported the function like this:
import { GlobalLogout } from '../src/helpers';
And finally use the function in the file like this:
GlobalLogout(data);
Hope this helps anyone!
Upvotes: 1
Reputation: 12991
2 methods, not sure which one is better:
Use:
window.foo = function(val) {
alert(val);
}
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
Reputation: 189
I have this helper function:
function myfunction(foo)
I declare it globally as:
global.myfunction = function myfunction(foo) {...};
Upvotes: 3