how to write plain javascript external function in react native?

965 Views Asked by At

I was trying to call a plain javascript function from an external file in react native but it is not running. Please suggest a way to inject a plain javascript function.

I have tried to use WebView:

<View style={{flex: 1}}>
    <WebView ref={ref => { this.webview = ref; }}
        source={{ html: HTML }}
        injectedJavaScript={jsCode}
        javaScriptEnabledAndroid={true}
        javaScriptEnabled={true}
    >
    </WebView>
</View>
2

There are 2 best solutions below

6
Zain Ul Abideen On

Create an external .js file write your code there.

module.exports.yourFuncName = (params) => {
     // your function def
} 

OR

module.exports.yourFuncName = function (params){
     // your function def
} 

In your Component simply import.

import { yourFuncName } from "location of file in code";

let jsCode = `
 yourFuncName(params)
`;

<View style={{flex: 1}}>
<WebView ref={ref => { this.webview = ref; }}
    source={{ html: HTML }}
    injectedJavaScript={jsCode}
    javaScriptEnabledAndroid={true}
    javaScriptEnabled={true}
>
</WebView>
0
Muhammad Umer Qadri On
module.exports.Example = (params) => { alert("123456") }

and then

import {Example} from 'fileName.js'

If its index.js file just specify the path of the folder