Aditya
Aditya

Reputation: 11

how to write plain javascript external function in react native?

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>

Upvotes: 1

Views: 1045

Answers (2)

Zain Ul Abideen
Zain Ul Abideen

Reputation: 1602

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>

Upvotes: 0

Muhammad Umer Qadri
Muhammad Umer Qadri

Reputation: 259

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

Upvotes: 0

Related Questions