I just wanted to encompass some JavaScript functions in a helper class. For example, running some fetch or async operations, etc. I do not want to create a Component class, instead it's just pure JavaScript. I don't think I can just create a js file, plop the code in and invoke it from within a Component. Do I need to register it, etc?
1 Answer
Yes you can through module imports. React native comes packed with babel compiler. You can reference all the enabled Syntax transformer at https://facebook.github.io/react-native/docs/javascript-environment.html.
Babel also has very good explanation on modules at https://babeljs.io/learn-es2015/#ecmascript-2015-features-modules.
For example:
File helper.js
export function doSomething(){
console.log("I am calling module helper through exported function")
}
File App.js
import {doSomething} from "./helper"; //simply imports function from another file.
import React, { Component } from "react";
import { AppRegistry, Text, View} from "react-native";
export default class ExampleComponent extends Component {
componentDidMount(){
doSomething(); //invoke your function here for example.
}
render() {
return (
<View>
<Text>I'm a text</Text>
</View>
)
}
}
AppRegistry.registerComponent("Example", () => ExampleComponent);
3 Comments
Charles Owen
Thanks, that worked. I've been going through some react-native tutorials, but they hadn't touched on the subject yet. I'm assuming that you could just as easily create an ES6 class with multiple functions, export it, and then import it into a Component.
Charles Owen
I was able to create an ES6 class with various methods I could reference as a utility class. Now I can reference these functions in multiple components.
Siwananda
Glad to know it helped :)