skip to Main Content

I have a React component that is sitting within a normal web page (so not a SPA).

There is a Vanilla JS function, within another JS function, on this webpage I wish to call from within my React component. This function looks like:

const getInfo = (() => {
  const updateInfo = (dataId) => {
    //Do something
  }
  const showInfo = (dataId) => {
    //Do something
  }
  return {updateInfo, showInfo}
})();

And they’re called on the (normal) webpages like:

getInfo.updateInfo("1324");

Now, I want to include this in my React component. So, I created a helper function, simply copying the above.

const getInfo = (() => {
  const updateInfo = (dataId) => {
    //Do something
  }
  const showInfo = (dataId) => {
    //Do something
  }
  return {updateInfo, showInfo}
})();

And calling it from within another helper function, as normal:

const calculate = () => {
   getInfo.updateInfo("1324");
   // Other React helper function stuff
}

However, when I try to compile I get the error

getInfo.updateInfo is not a function

Would anyone know how I can use getInfo.updateInfo(); within my React component’s helper functions?

2

Answers


  1. Unfortunately, you haven’t provided complete information about the structure of your component, so it’s likely that no one will be able to give you a definitive answer.
    If this function is defined outside the component, it must either be imported directly or passed to the component as props to be accessed.
    If you’re using a helper function, you need to ensure it receives the required parameters; otherwise, React won’t recognize what getInfo.updateInfo() is and will throw an error.

    Login or Signup to reply.
  2. One of the ways to do this is to attach this to the window object.
    In your vanilla js script:

    const getInfo = (() => {
      const updateInfo = (dataId) => {
        //Do something
      }
      const showInfo = (dataId) => {
        //Do something
      }
      const getInfoObject = {updateInfo, showInfo};
      window.getInfo = getInfoObject;
      return window.getInfo;
    })();
    

    And now window.getInfo is available for anyone to use. You can use it in your React component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search