-1

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?

code

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87

4 Answers4

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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>
 )
}
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

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.

Vars Zakaryan
  • 251
  • 2
  • 6
0

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

synalgic
  • 1
  • 1