Why is there a comma in the React import statement? - javascript

When creating a React app there's the common:
import React, {Component} from 'react';
import statement. I'm curious why the line requires a comma? I've tried looking this up and cannot find an explanation.

Foo.js
export const bar = "bar";
export default "baz";
or:
export const bar = "bar";
const baz = "baz";
export default baz;
bar is a named export and must be imported with {}.
baz is the default export and can be imported with any name without {}.
import baz, { bar } from "Foo";
console.log( baz, bar );
or
import bazButIwantFizz, { bar } from "Foo";
console.log( bazButIwantFizz, bar );
or
import bazButIwantFizz, { bar as barButIWantBuzz };
console.log( bazButIwantFizz, barButIWantBuzz );
So, we can import named and default exports separating with a comma.
As suggested in the comments, refer to the related documentation.

The React is the default export from 'react'.
After the comma comes a list of other exports from 'react'.
As mentioned in the MDN docs the syntax for an import statement can look like this:
import defaultExport, { export [ , [...] ] } from "module-name";

You must be using JSX (html syntax) in the file, which requires React as an import dependency, exported as default from 'react' module.
Then you import Component as a named import, denoted in JS within {}. There are other things like {Fragment, createElement} that you can do if required.
Refer MDN for more.

As #Derek said in the comment above. This is one possible syntax for import.
link shamelessly stolen from #Derek

Related

ES6 Import Scenario

There are multiple way to import modules. What is the difference between import {House} and import House?
There are two way to import in ES6 module, based on the export option.
Named Import
//filename - simple.js
export function Simple() {}
import {Simple} from "./simple.js"
Default Import
//filename - simple.js
export default Class Simple {}
import Simple from "./simple.js"
For more, refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
UPDATE
You can also export both from a single file and import them. Important caveat here is there can be only one default export in a module.
//filename - simple.js
export function Simple1() {}
export default function Simple2() { }
import Simple2, { Simple1 } from "./simple.js"
The syntax import {House} is used to import specific, named imports like import {foo, bar} from '/modules/my-module.js';
while the syntax import House is used to import default exports like import myDefault from '/modules/my-module.js';
As one can see that we can mix these two. For example, this is also a valid import
import myDefault, {foo, bar} from '/modules/my-module.js';
to read more checkout Mozilla developer guide.

Named import in React

In this line:
import React, { Component } from "react";
why the braces are only around Component and not also on 'React'?
Here's a great answer that explains default and named imports in ES6
Let's say we have a class named Foo that I want to import. If I want to get the default export, I would do:
import Foo from './foo.js';
If I wanted a specific function inside the foo file, I would use the curly braces.
import { fooFunction } from './foo.js';
Note, this isn't a React feature, but ES6. Likely you are using babel to transpile your code from ES6 to ES5.
To create something similar in react. Lets take this following example.
someobject.js
const someobject = {
somefunc1: ()=>console.log("hello 1"),
somefunc2: ()=>console.log("hello 2")
}
export default someobject;
app.js
import someobject, { somefunc1, somefunc2 } from "./someobject";
someobject.somefunc1(); //hello 1
someobject.somefunc2(); //hello 2
somefunc1(); //hello 1
somefunc2(); //hello 2
export defaul
In the React module the default export is the React object and it also has a named export Component1, something like this:
// assuming React and Component are predefined
export default React
export Component
Coincidentally Component is also available on the React object, so it is not necessary to import separately, although some people prefer your approach. For example this is possible:
// MyComponent.js
import React from 'react'
class MyComponent extends React.Component {}
More information about ES6 module syntax can be found here.
1 Note that actually the React library does not have a named export Component as in the example above, however Component is a property on the default export and so due to the way that ES6 packages are transpiled by Babel, this becomes a named export, the behaviour then being as in the example above.
Import react will import the default react package, Component with braces then specifies a particular element of the React package. React by default will not need braces as it is the default import package.
import React, { Component } from "react";
Hope this helps
That is because the default export module in the react library is React, and there can be only one default export, even though you can export many other components, but only one can be default. Other components of the React library can then be destructured.
React is a module containing different methods, When using just React word, you import the whole module, so you can use React.Component (in this case dot notation reference to a method inside the module).
So if you need to import method? you will use braces, why?
because you import method between many methods in one module, So it's able to increase & decrease, so you can import {a, b, c, r, w, q} that's methods inside one class or one module, So you can see that if you using
import {Component} from 'react';
Now you can use Component word direct without dot reference like react.component.
So React module is exported by default, Here I need all the React module and I will use it with all methods, {Component} here exported by name, I need specific method from React library not all react library
and please check it too When should I use curly braces for ES6 import?
in the import import React, { Component } from "react"; we put the Component in braces because it is not the default export. however React is,... look at the following example
import React from "react";
export const Fun1 = () => {
return (
<React.Fragment>
<h1>this is fun 1</h1>
</React.Fragment>
);
};
export const Fun2 = () => {
return (
<React.Fragment>
<h1>this is fun 2</h1>
</React.Fragment>
);
};
const Fun3 = () => {
return (
<React.Fragment>
<h1>this is fun 3</h1>
</React.Fragment>
);
};
export default Fun3;
if we save the above file under example.js we can import the components in exmpample.js file as
import Fun3, {Fun1, Fun2} from "example";
therefore Fun3 is the default export and the other components Fun1 and Fun2 are not

React: Understanding import statement

What is the difference between these two statements
import React from 'react';
and
import React, { Component } from 'react';
Shouldn't import React from 'react' import everything including the content? What should I read to understand this?
You can read about this here.
Importing something without curly braces imports whatever was defined as the default export in the module from which you are importing. There can only be exactly one (or no) default export in a module.
foo.js:
const myObject = {foo: 'bar'};
export default myObject;
bar.js:
import theObject from './foo';
console.log(theObject);
// prints {foo: 'bar'}
// note that default exports are not named and can be imported with another name
Importing with curly braces imports what was exported as a named export with that name by the module. There can be multiple named exports in a module.
foo.js:
export const myObject = {foo: 'bar'};
export const anotherObject = {bar: 'baz'};
bar.js:
import {myObject, anotherObject, theObject} from './foo';
console.log(myObject);
// prints {foo: 'bar'}
console.log(anotherObject);
// prints {bar: 'baz'}
console.log(theObject);
// prints undefined
// because nothing named "theObject" was exported from foo.js
With
import React, { Component } from 'react';
you can do
class Menu extends Component { /* ... */ }
instead of
class Menu extends React.Component { /* ... */ }
from this: Import React vs React, { Component }
This is the ES6.
import Raect, { Component } from 'react';
Like
import default_export, { named_export } from 'react';
Consider two file. Person.js like
const person = {
name: 'johon doe'
}
export default person; // default export
Utility.js like
export const clean = () => { ... } //named export using const keyword
export const baseData = 10; //named export using const keyword
inport in App.js file. like
import person from './Person';
import prs from './Person';
import {clean} from './Utility';
import {baseData} from './Utility';
import {data as baseData} from './Utility';
import {* as bundled} from './Utility';
//bundled.baseData
//bundled.clean
João Belo posted a great answer to read, but I'll add one more thing. the second instance is using destructuring and object-shorthand to grab the 'Component' property's value from the react module and assign it to a 'Component' variable that you can use locally. If you don't know about destructuring and object-shorthand, you should definitely look them up. They come in handy.
Primarily, this boils down to the way you export variables. I believe, this must be a deliberate design decision from Facebook contributors.
export default class ReactExample {}
export class ComponentExample {}
export class ComponentExampleTwo {}
in the above example, ReactExample can be imported without using {}, where as the ComponentExample, ComponentExampleTwo , you have to import using {} statements.
The best way to understand is going through the source code.
React export source code
React Component source code
import * as myCode from './../../myCode';
This inserts myCode into the current scope, containing all the exports from the module in the file located in ./../../myCode.
import React, { Component } from 'react';
class myComponent extends Component { ... }
By Using above syntax your bundler ( e.g : webpack) will still bundle the ENTIRE dependency but since the Component module is imported in such a way using { } into the namespace, we can just reference it with Componentinstead of React.Component.
For more information you can read mozilla ES6 module docs.

What is the difference between with and without curly bracket notation in export/import statements?

I'm new to ES6 and a bit confused with the way classes are exported and imported. It seems many different notations are valid but work differently.
I wrote a class like this in src/web-api.js:
class WebApi {
// ...
}
export { WebApi };
Which I import with:
import { WebApi } from './src/web-api.js'
This works fine, but before I've tried the same thing without curly brackets and it didn't work:
export WebApi; // Tells me '{' expected
import WebApi from './src/web-api.js'; // No syntax error but WebApi is undefined
Even though on the MDN documentation for export, the notation export expression; appears to be valid.
Likewise, this is how React is imported in my application file:
import React, { Component } from 'react';
Why is one class with and another one without curly brackets? In general, how can I tell when to use and not to use curly brackets?
ES6 offers many ways to manage modules through import/export. But there are basically two main strategies:
Default export/import with export default and import module from './module'
Multiple exports/imports with export and import {member} from './module' or import * as module from './module'
(Mixing both is possible but not recommended.)
Module to export/import
function foo() {
console.log('Foo');
}
function bar() {
console.log('Bar');
}
Strategy #1: Default export/import
Export (module.js)
function foo() {
console.log('Foo');
}
function bar() {
console.log('Bar');
}
export default {foo, bar};
/*
{foo, bar} is just an ES6 object literal that could be written like so:
export default {
foo: foo,
bar: bar
};
It is the legacy of the "Revealing Module pattern"...
*/
Import (main.js)
import module from './module';
module.foo(); // Foo
module.bar(); // Bar
Strategy #2: Multiple exports/imports
Export (module.js)
export function foo() {
console.log('Foo');
}
export function bar() {
console.log('Bar');
}
Import (main.js)
import {foo, bar} from './module';
foo(); // Foo
bar(); // Bar
/*
This is valid too:
import * as module from './module';
module.foo(); // Foo
module.bar(); // Bar
*/
As I said previously, ES6 modules are much more complex than that. For further information, I recommend you to read Exploring ES6 by Dr. Axel Rauschmayer, especially this chapter: http://exploringjs.com/es6/ch_modules.html.
In your case, if you import from the src/web-api.js file without the curly braces, you should have anexport default something in the src/webfile-api.js
Without curly braces
class WebApi {...};
export default WebApi;
In your file
import WebApi from './src/web-api.js'
// Here, the element withexport default in the src/web-api.js file should be imported without the curly braces anywhere.
PS: It must have only one export default for each file.
With curly braces
export { WebApi }
In your file
import {WebApi} from './src/web-api.js'
Dan Abramov explains clearly the export/import methods in ES6 at this answer.
When should I use curly braces for ES6 import?
The braces are just syntactic sugar. It will use the variable name as the object key, for example:
const a = 1;
const test = {a}; // same as {a: 1};
It can also be used to destructure the object by its variable name. It will check if the object has any properties with the same value as the variable name and then output a value if one is found:
const test = {a: 1};
const {a} = test; // a = 1
In modules, the general use case is that when you import there is usually braces since modules get imported as MODULE.function or MODULE.class. It'd be more intuitive to look at exports first:
For exporting, it's using the syntactic sugar I mentioned before - you're exporting it as an object. When you do export { WebApi }; what you're really doing is export {WebApi: WebApi}. This makes it easier to access things as you can just do 'MODULE.WebApi' now to access the class instead of having it pollute the namespace unnecessarily. This is also required for all exports!
Moving on to imports, what you're doing in the import statements is essentially destructuring the module object and picking a property to save into a variable of the same name. In your case, when you do import {WebApi} from './src/web-api.js' you'd be doing something like import WebApi = web-api.js['WebApi'] from './src/web-api.js' (this isn't valid syntax but just to show you what it's doing in the background). This is also required to properly import module functions/classes. There is also the option of importing the whole module, just as NodeJS does: import * as ModuleName from './src/module.js'. This will put all of exported functions/classes into the ModuleName object so that it can be treated as a normal module.
However, if a module has a default export, braces are not not needed for import and export. For example, react probably has export default React in its files - that's why there doesn't need to be braces around it when you do import React from 'react'
Hope I wasn't too confusing and let me know if I can clarify anything!

How to import part of object in ES6 modules

In the react documentation I found this way to import PureRenderMixin
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
How can it be rewritten in ES6 style. The only thing I can do is:
import addons from "react/addons";
let PureRenderMixin = addons.addons.PureRenderMixin;
I hope there is a better way.
Unfortunately import statements does not work like object destructuring. Curly braces here mean that you want to import token with this name but not property of default export. Look at this pairs of import/export:
//module.js
export default 'A';
export var B = 'B';
//script.js
import A from './a.js'; //import value on default export
import {B} from './a.js'; // import value by its name
console.log(A, B); // 'A', 'B'
For your case you can import whole object and make a destructuring assignment
import addons from "react/addons";
let {addons: {PureRenderMixin}} = addons;
import PureRenderMixin from 'react-addons-pure-render-mixin';
See example here.

Categories

Resources