Anyone know in reactjs how to be able to call that 'openSideMenu' function which is in the vanilla js file that I imported on the top?
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import – Roberto Zvjerković May 17 '21 at 12:34
-
See [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export). – Ajeet Shah May 17 '21 at 12:34
-
Pease read [ask]. In particular the part about not posting pictures of text. – Quentin May 17 '21 at 12:36
-
Please don't use screenshots of your code, it's not very accessible. – JustCarty May 17 '21 at 15:21
4 Answers
You can't.
The function will be scoped to the module and inaccessible outside it.
Rewrite the module you are importing so it exports the data you need.
A dirty hack would be to:
- Load the JS file using a
<script>
element - Ensure that it sets the function as a global
- Access
window.thatfunction
inside the React app
but that's fiddley and has the usual problems of globals.

- 914,110
- 126
- 1,211
- 1,335
To further what Quentin said, you're not doing react in a react-y way. To be clear, it's always going to be harder and more confusing to do stuff the wrong way when dealing with react.
The react way to do what you want is something like this:
function NavBarLogo({onLogoClick}) {
return (
<nav>
<img ... onClick={onLogoClick}/>
<img ... />
</nav>
)
}
Whatever renders NavBarLogo
looks something like this:
function NavBarContainer() {
cons [className,setClassName] = React.useState('closed');
const handleLogoClick = () => setClassName(c => c === 'closed' ? 'opened' : 'closed')
return (
<div className={className}>
<NavBarLogo onLogoClick={handleLogoClick}>
... other stuff
</div>
)
}

- 51,445
- 11
- 72
- 100
If you exported your openSideMenu function in your sideMenuFunction.js file as default, then you need to import like this:
import openSideMenu from '../../utils/sideMenuFunction';
if not as default, then you need to import like this:
import { openSideMenu } from '../../utils/sideMenuFunction';
Make sure the names are the same both where you import and from where you import and it will work fine.

- 251
- 2
- 6
When you want to call an external function, you have to export it from the file it's contained in.
So in your example, you would want to have:
import { openSideMenu } from '../../utils/functions.js';
and then in 'functions.js' you would have:
export const openSideMenu = () => {
// Do Stuff Here...
}
And then you'll have no problem calling 'openSideMenu' from your onClick just how you have it

- 1
- 1