1

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>
epanalepsis
  • 853
  • 1
  • 9
  • 26
Aditya
  • 11
  • 2

2 Answers2

0

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>
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25
  • Hi Zain , thank for reply but I need to use/import a JavaScript plugin in React-native. Plugin file contains functions, written in javascript and not in es6 format. I need to use those in react-native either by Webview or can be other way. I already tried WebView, But html code is not even loading JS plugin file ( – Aditya Nov 03 '20 at 08:33
  • It does not matter how your plugin file is written, you just need to call the function in your component. Can you share the content of your plugin file? Also what are you getting when trying to use simple import on your exported function? – Zain Ul Abideen Nov 03 '20 at 09:09
  • plugin file function module.exports.Example = (params) => { alert("123456") } when i imported it on component and use it in attribute tag it is saying example is not a function undefined import {Example} from "../../login/index" – Aditya Nov 03 '20 at 11:36
  • I've updated my answer can u try this approach? thanks – Zain Ul Abideen Nov 03 '20 at 13:27
  • Hi Zain , it is working your updated approach, here is link of my external file code. https://drive.google.com/file/d/1LhLBgI5_U_GyJpitU_-HNaUXj20M0xY7/view can you please provide any suggestions on this code, we have number of functions – Aditya Nov 04 '20 at 09:28
  • That's nice. If it's working then you can consider upvoting and accepting the answer. Thanks – Zain Ul Abideen Nov 04 '20 at 09:38
0
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