Search code examples
javascriptreactjstsx

How to Call javascript function from js file with parameter and return data from tsx file?


I have one js file as sample.js which has function like below:

function checkLogin(userName, password) {
  var returnvalue = '';
  //logic for login and assign value in returnvalue variable
  return returnvalue;
}

I want to call this function from my .tsx file how can I do it?


Solution

  • Do you have access to modify the sample.js? If so, try adding export in front of your function; ie. exportfunction checkLogin(userName, password) {...}. Then, import this script in your TSX file using require like:

    var Sample = require("./sample.js");
    

    Note this example assumes sample.js lives in the same path as your TSX file, but you can modify as needed.

    Then, you should be able to access your function by way of calling Sample.checkLogin(..., ...); in your TSX.

    Alternative

    If you are able to change make your "sample" script into a TypeScript (TS) file (sample.ts), you would still add export in front of your function and probably want to add types like string to the two function parameters:

    export function checkLogin(userName: string, password: string) {...}
    

    Then, you can use import in your TSX file, instead:

    import * as Sample from "./sample";
    

    This also assumes your sample.ts lives in the same path as your TSX and would allow you to make calls to Sample.checkLogin(..., ...); in your TSX.