ehuff
ehuff

Reputation: 119

Having Trouble Accessing Function in Adjacent JS file

Currently in my directory I have App.js and startMenu.js as two separate files. I would like to access startMenu.js in my App.js file with the correct React formatting. Currently I can call the function startMenu() using typical javascript syntax, but I for some reason cannot get the React syntax {startMenu} to work. Any ideas would be appreciated.

My code:

import React from "react";
import startMenu from './startMenu';
import credits from "./credits";

var param = 'start';

class App extends React.Component {
  renderSwitch(param) {

    switch(param) {
      case 'credits':
        return credits();
      default:
        /*LINE IN QUESTION */ 
        return startMenu();
    }
    
  }
  
  render() {
    return (
      <div>
        {this.renderSwitch(param)}
      </div>
    );
  }
}

export default App;

Thanks!

Upvotes: 0

Views: 47

Answers (3)

Emmanuel Kant Duarte
Emmanuel Kant Duarte

Reputation: 24

It is depending how you are exporting your function.

If is doing this:

export default startMenu;

Then you might import that way:

import myFunction from './path';

That way the name does it care. You can call your function with any name when you are exporting by default.


But if you are exporting that way:

export { startMenu };

or

export startMenu;

So than you need import your function by your reall name, and if you are exporting just using export word, all members will be inside an object.

So you need do that:

import MyFunctions from './path';

or doing a import destruction

import { startMenu } from './path';

Upvotes: 1

Quentin
Quentin

Reputation: 943569

The JSX syntax: {foo} means "Put this data here".

It doesn't mean "Call this variable as a function".

If you want to call it, you need to do so explicitly: {foo()}.

Upvotes: 0

tadman
tadman

Reputation: 211590

You'll need to properly export that function:

export function startMenu(...) { ... }

Then import it:

import { startMenu } from './startMenu';

If that's the only thing exported you can always export default and it simplifies the import.

You can only import things that have been exported. Everything else is considered private and is off-limits.

Upvotes: 0

Related Questions