0

I have a react.js file MyComponent that has this at the end: module.exports = MyComponent, where MyComponent is a function defined in the file.

What if I want to export ANOTHER function: MyHelperComponent from the same file, so that another react component from another react.js file may use MyHelperComponent directly ?

So my question is: how do I export a function that is not the 'main' component of the module ?

user1008636
  • 2,989
  • 11
  • 31
  • 45
  • Does this answer your question? [Declare multiple module.exports in Node.js](https://stackoverflow.com/questions/16631064/declare-multiple-module-exports-in-node-js) – Amar Syla Jun 05 '20 at 14:03
  • Did you try google? https://create-react-app.dev/docs/importing-a-component – Dennis Vash Jun 05 '20 at 14:11

3 Answers3

1

You can only export one value from a module.

If you need to use multiple values outside it, then you need to group them somehow. Typically you would put them in an object and then export that object.

module.exports = { MyComponent, MyHelperComponent };

And then:

const MyComponent = require("./mymodule.js").MyComponent;
const MyHelperComponent = require("./mymodule.js").MyHelperComponent;

or

const mymodule = require("./mymodule.js")
const MyComponent = mymodule.MyComponent;
const MyHelperComponent = mymodule.MyHelperComponent;

or

const {MyComponent, MyHelperComponent} = require("./mymodule.js");

That said, it is usual to structure code on a one-component-per-module basis, so you might want to rethink doing this in the first place.

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

You can do it like this:

//...function defs here

MyComponent.helper = MyHelperComponent
module.exports = MyComponent

And then just access MyComponent.helper(args) to call the helper function.

Jason Kennaly
  • 622
  • 1
  • 5
  • 9
-1

You can export like this: export { component1, component2 } And use like this: import { component1, component2 } from './url' or import * as components from './url' <components.component1 /> Hope helpful...