React: Understanding import statement - javascript

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.

Related

TypeError: X is not a constructor

I am learning React and ES6. I Created a React ES6.js for using and learning es6 features comfortably and cleanly.
Then I imported this js file in index.js and used that way:
// Get Started
import React from 'react';
import ReactDOM from 'react-dom';
const myfirstelement = <h1>Hello React!</h1>
ReactDOM.render(myfirstelement, document.getElementById('root'));
// React ES6 (ES6 stands for ECMAScript 6.)
// eslint-disable-next-line
import { Car } from './ReactES6'
var mycar = new Car("Ford");
mycar.present();
document.write(mycar.brand);
Also ./ReactES6:
// eslint-disable-next-line
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
I am getting an error in the title of this question while running but compiler doesn't gives any error.
What I am doing wrong, please help me experienced friends.
Probably something with the way you are exporting Car from ReactES6. It doesn't show in the code if you are exporting it. You could export it using
export default Car
at the bottom of the file. Then in the main method import it using
import Car from './ReactES6'
Edit: Notice that I removed the curly braces from the import statement { }. If you want to import something like { Car } you need a named export. A file can have multiple named exports, but only one default export. Try reading about Named Exports vs Default exports.
Here's a relevant SO thread

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.

Why do we have to use “*” while importing in typescript? [duplicate]

What is the difference in TypeScript between export and default export?
In all the tutorials, I see people exporting their classes and I cannot compile my code if I don't add the default keyword before exporting.
Also, I couldn't find any trace of the default export keyword in the official TypeScript documentation.
export class MyClass {
collection = [1,2,3];
}
Does not compile. But:
export default class MyClass {
collection = [1,2,3];
}
Does.
The error is:
error TS1192: Module '"src/app/MyClass"' has no default export.
Default Export (export default)
// MyClass.ts -- using default export
export default class MyClass { /* ... */ }
The main difference is that you can only have one default export per file and you import it like so:
import MyClass from "./MyClass";
You can give it any name you like. For example this works fine:
import MyClassAlias from "./MyClass";
Named Export (export)
// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }
When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:
import { MyClass } from "./MyClass";
Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.
Or say your file exported multiple classes, then you could import both like so:
import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass
Or you could give either of them a different name in this file:
import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias
Or you could import everything that's exported by using * as:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here
Which to use?
In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.
Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.
That said, find what you prefer! You could use one, the other, or both at the same time.
Additional Points
A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:
import { default as MyClass } from "./MyClass";
And take note these other ways to import exist:
import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo'; in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo' in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in Avoid Export Default
Named export
In TypeScript you can export with the export keyword. It then can be imported via import {name} from "./mydir";. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same directory
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import, export, and export default are JavaScript constructs, not TypeScript. However, TypeScript added the exporting and importing of interfaces and type aliases to it.
Here's an example with simple object exporting.
var MyScreen = {
/* ... */
width : function (percent){
return window.innerWidth / 100 * percent
}
height : function (percent){
return window.innerHeight / 100 * percent
}
};
export default MyScreen
In the main file (use it when you don't want and don't need to create a new instance) and it is not global, you will import this only when it is needed:
import MyScreen from "./module/screen";
console.log(MyScreen.width(100));

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

Why is there a comma in the React import statement?

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

Categories

Resources