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
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.
One of the ways to do this is to attach this to the window object.
In your vanilla js script:
And now
window.getInfo
is available for anyone to use. You can use it in your React component.