Multiple exports from react.js file - javascript

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 ?

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.

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.

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...

Related

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!
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';
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.
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()}.

Javascript export default and import

I have the following code:
const API1 = new API({
...
})
const API2 = new API({
...
})
export default { API1, API2 }
I need to import like this:
import API1 from '/lib/api'
API1.get()...
But it doesn't work.
I don't want to do this:
import blah from '/lib/api'
blah.API1.get()...
How can I solve this ?
Thanks.
If you need to export multiple items, and don't want to have to create two variables in the consuming module (one for the default import - the object, and another for the API1 property), your only other option is to change the default export to a named export, allowing you to import just one particular named property:
const API1 = new API({
...
})
const API2 = new API({
...
})
export { API1, API2 }
and
import { API1 } from '/lib/api'
API1.get()...
The export { syntax indicates that the export is named, rather than default, and the import { syntax indicates that you're importing a named import, rather than a default import.
(It looks a lot like destructuring, and it's a little bit similar, but it's not the same)
Since you're default exporting an object you need to access individual property to access there methods, Instead you can use named exports
// exporting values
export const API1 = new API({
...
})
export const API2 = new API({
...
})
// Importing values
import { API1 } from '/lib/api'
API1.get()...

How to Export Variables with a Dynamic Names

I have a components folder in nuxt.js
/components/atoms/
and inside that folder I have an index.js to export all components dynamically
const req = require.context('./', true, /\.vue$/)
const components = {}
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
components[componentName] = req(fileName).default
})
export const { ButtonStyled, TextLead, InputSearch } = components
so I can import perfectly as I wish
import { ButtonStyled } from "#/components/atoms"
the problem is that I am defining the variables to be exported statically, fixed, so for each created component I would need to add another variable manually
I need to dynamically export the variable name
Example:
DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']
export const { DynamicCreation } = components
// output -> export const { ButtonStyled, TextLead,InputSearch } = components
I need to export the name of already unstructured variables
Note: I can not use this export default components because I can not import like this import { ButtonStyled } from "#/components/atoms"
You should be able to do it like this:
export default components
Then in your file where you want to use the components:
import * as components from '#/components/atoms'
Then when you need to use the components in your Vue files, you need to map them:
#Component({
components: {
ButtonStyled: components.ButtonStyled
}
})
And now you have:
<ButtonStyled></ButtonStyled>
You can make something like this way, check if is what do you need.
Create a file to import a conjunct of components: allComponents.js
export default {
componentOne: require('./passToOneComponent.js');
componentTwo: require('./passToOneComponent.js');
componentThree: require('./passToOneComponent.js');
}
After in index.js export the allComponents.js with the name that you wish:
export {default as SomeName } from 'allComponents.js';
So in the final file, you can make something like:
import { SomeName } from 'index.js';
SomeName.componentOne();
I created a library that does this type of export, anyone who wants can install via npm
I created a Webpack Plugin that makes named exports from a component, maybe this helps other people
Weback Plugin - named-exports

React: export function with connected function

I know how to connect my translate function to a component this way:
class App extends Component {
...
}
export default translate('common')(App);
But how can I do the same task if component is being exported this way:
export function UserInterface({data, onAdmin, isAdmin}: propTypes){
...
I know, that this is kind of silly question. But I am stuck at this point.
You can write something like this:
export const UserInterfaceWithTranslation = translate('common')(UserInterface);
Please read more about exports.
You can export functions too
MyContext.js
function UserInterface({data, onAdmin, isAdmin}: propTypes){
... some code
}
module.exports = {
userInterface : UserInterface
}
Import
import myContexts from './MyContext'
myContexts.userInterface(params);

Correct way to export object in es6 module

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium.com/#rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38)
So I was wondering what's the correct way to export an object and then use it as
import utils from "./utils"
`
utils.foo()
Currently I'm doing like so
/** a.js **/
function foo(){
//...
}
export {
foo
}
/** b.js **/
import * as utils from "a";
utils.foo()
is it correct like so? Do I maintain the tree-shaking feature?
thanks
If the object you want to import/export only contains some functions (as I assume due to the Utils name), you can export the functions separately as follows:
export function doStuff1() {}
export function doStuff2() {}
And import like this:
import {doStuff1, doStuff2} from "./myModule";
However, if the object you want to export holds state in addition to methods, you should stick to a simple export default myObject. Otherwise, calling the imported methods won't work as intended, since the context of the object is lost.
As an example, the following object should be exported as a whole, since the properties of the object should stay encapsulated. Only importing and calling the increment function would not mutate myObject since the context of the object cannot be provided (since it's not imported as a whole).
const myObject = {
counter: 0,
increment: function() {
this.counter++;
}
}
export default myObject;
es6 native way to do this:
// file1.es6
export const myFunc = (param) => {
doStuff(param)
}
export const otherFunc = ({ param = {} }) => {
doSomething({ ...param })
}
// file2.es6
import { otherFunc } from './file1.es6'
import * as MyLib from './file1.es6'
MyLib.myfunc(0)
MyLib.otherFunc({ who: 'Repley' })
otherFunc({ var1: { a1: 1 } })
And so on.

Categories

Resources