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?
-
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Roberto Zvjerković– Roberto Zvjerković2021-05-17 12:34:14 +00:00Commented May 17, 2021 at 12:34
-
See import and export.Ajeet Shah– Ajeet Shah2021-05-17 12:34:26 +00:00Commented May 17, 2021 at 12:34
-
Pease read How to Ask. In particular the part about not posting pictures of text.Quentin– Quentin2021-05-17 12:36:13 +00:00Commented May 17, 2021 at 12:36
-
Please don't use screenshots of your code, it's not very accessible.BritishWerewolf– BritishWerewolf2021-05-17 15:21:21 +00:00Commented May 17, 2021 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.thatfunctioninside the React app
but that's fiddley and has the usual problems of globals.
Comments
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>
)
}
Comments
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.
Comments
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
