Search code examples
javascriptreactjsfunctionundefined

How can i access a function?


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?


Solution

  • 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";