-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

4

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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>
 )
}

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.