1

So, for example, I have this index.js react file:

import React from "react";
import Helmet from "react-helmet";
import MyScript from "../javascript/myscript";

function Index(){
   return(
      <div id="index">
          <Helmet> 
              <script type="text/javascript" src="https://example.com/functions.js"/>
          </Helmet>
          <h1>Hello, test</h1>

          {MyScript()}
      </div>
   );
}

export default Index;

Then, the https://example.com/functions.js looks like this:

function Salute(){
   return console.log("Hello, world!");
}

function SayGoodBye(){
  return console.log("Good bye, world!")
}

And MyScript looks like this:

   Salute();

or:

   SayGoodBye();

I tried calling the function Salute from MyScript, but I get an error saying Salute is not defined. How can I call the Salute function from MyScript?

David
  • 23
  • 3
  • You shouldn't be calling it like that, you can return a JSX from Salute function and not a console log – Plvtinum Dec 24 '22 at 11:21

1 Answers1

1

You need to export them first

export function Salute(){
   return console.log("Hello, world!");
}

export function SayGoodBye(){
  return console.log("Good bye, world!")
}

and then you can import them as

import {Salute, SayGoodBye} from "../javascript/myscript";
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • yeah, but how do i import them if the functions are in "https://example.com/functions.js"? i can't do import{Salute, SayGoodBye} from "https://example.com/functions.js" – David Dec 24 '22 at 11:56
  • Refer this question for adding script in react - https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx – Arjun Dec 24 '22 at 12:41