'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?
Solution 1:[1]
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'
Solution 2:[2]
2 methods, not sure which one is better:
- Method
Use:
window.foo = function(val) {
alert(val);
}
- (Not really global) Inside your
classwhere you export and require in theneed-to-usefile, 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;
Solution 3:[3]
I have this helper function:
function myfunction(foo)
I declare it globally as:
global.myfunction = function myfunction(foo) {...};
Solution 4:[4]
I did in a simple way like this:
I created a
helpers.jsfile 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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | c-chavez |
| Solution 3 | c-chavez |
| Solution 4 | Aqeeb Imtiaz Harun |
