I can see there are two different ways to import:
import React from 'react'
import { render } from 'react-dom'
The second one has brackets. What is the difference between the two? And when should I add brackets?
Well, the difference between whether you should import your components within brackets or without it lies in the way you export it.
There are two types of exports
Default Export
Named Export
A component can have one default export and zero or more named exports.
If a component is a default export then you need to import it without brackets.
E.g.,
export default App;
The import it as
import App from './path/to/App';
A named export could be like
export const A = 25;
or
export {MyComponent};
Then you can import it as
import {A} from './path/to/A';
or
import {A as SomeName} from './path/to/A';
If your component has one default export and few named exports, you can even mix them together while importing
import App, {A as SomeName} from './path/to/file';
Similarly in case of react and react-dom, React and ReactDOM are default exports respectively whereas, for instance Component is a named export in react and render is a named export in react-dom. That's the reason you can either do
import ReactDOM from 'react-dom';
and then use
ReactDOM.render()
or use it like mentioned in your question.
First of all, a big thank you to all the other answers.
Here is a summary of all the above, in one answer.
Context with examples
import React from 'react'; // Importing without braces
import { render } from 'react-dom'; // Importing with braces
To be able to understand import, it's important to firstly understand export and its types.
Types of exports
There are mainly two types of exports, 'default' and 'named'. Whether to use braces or not, depends entirely on which type of exported variable is being imported.
So, the short answer is that variables exported as default, do not need braces, but named variables do need to be imported with braces.
Now, let's look at some practical examples of how to import and export both types.
Default: How to export and import
exporting
// Module1.js
export default App;
// Module2.js
export default myVariable;
// Module3.js
export default myFunction;
// Please note that there can only be one default export per module!
importing
import App from './Module1'
import AppRenamed from './Module1'
import myVariable from, './Module2'
import myFunction from './Module3'
// Please note that default modules can be renamed when importing
// ... and they will still work!
Named: How to export and import
exporting
export const A = 42
export const myA = 43
export const Something = 44
export { cube, foo, graph };
// Note how there can be several named exports per module
// exported in groups or individually
importing
import { A, myA } from './my-module.js';
import { Something as aRenamedVar } from './my-module.js';
import { cube } from './my-module.js';
import { foo, graph } from './my-module.js';
// Likewise, named exports can be imported in groups or individually
Other notes
let's revisit the very first example we saw above
import React from 'react'
import { render } from 'react-dom'
please note that although, React doesn't use braces, and render does, render is actually a part of react-dom.
therefore it is also possible to import the entire default react-dom
without braces and then use render
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render()
Consider primitives.js,
export default (a, b) => a + b;
export const sub = (a, b) => a - b;
export const sqr = a => a**2;
It can be imported like this,
import sum, { sub, sqr } from './primitives';
In this case, sum is called a "Default Export" and a module may contain a single "Default Export" only.
sub and sqr are called "Named Export" and a module may contain multiple named exports.
Curly braces are used to import single(specific) property, whereas the word without braces is import entire object form that file.
For example,
import React, { Component } from 'react';
Here the word React represents to import entire object from the file 'react'.
{Component} means we specify to import the particular property from the file.
There isn't any need to add brackets if you are exporting as default. You can have only default in the module.
Case 1:
export default function(num1, num2) {
return num1 + num2; }
Case 2:
function sum(num1, num2) {
return num1 + num2; }
export { sum as default };
Case 3:
function sum(num1, num2) {
return num1 + num2; }
export default sum;
You can import the default
import sum from "./test.js";
console.log(sum(1, 2));
Related
how to use import statement to import functions from one component to other component.
Below is how the import statement is:
import Tool from '../Common';
import { ToolContextProvider } from '../Common';
This complaint of duplicate lines. So I have tried something like below,
import { ToolContextProvider, Tool} from '../Common';
But this doesn't seem to be correct. How can write this in one line.
Could someone help me with this? Thanks.
basically there are two different type of export in javascript modules (also react included):
default export
named export
default export would be like :
// someFile.js
export default SomeComponent
named export would be like
// someFile.js
export SomeOtherComponent
importing them in other components for using them should be like:
// useCase.js
import SomeComponent from './someFile' // for default export
import { SomeOtherComponent } from './someFile' // for named export
import SomeComponent, { SomeOtherComponent } from './someFile' // for using both
You can import like this. Just combine both of them.
import Tool, { ToolContextProvider } from '../Common';
Hello i need to have a multiple export in react js but i have this error
Line 84:3: Parsing error: Only one default export allowed per module.
this is my code :
export default App;
export default dashboardRoutes;
What i should to do to resolve this problems please !
You can export only one default component and the other like this:
export default MostImportantComponent
// other components
export {
Component1,
Component2,
// ... etc
}
Notice that when you import the other components from other files you need to
import DefaultComponent from '...'
import { Component1, Component2 } from '...' // for other components
There are basically two types of exports.
1.Named Exports(Zero or more exports per module): This allows you to export multiple modules from a javascript file which is the case in your issue.
Solution to your case goes as follows
modules.js
export {
App,
DashboardRoutes
};
app.js
import {App,DashboardRoutes} from './modules.js'
You can equally change the names of those modules in the import file as follows
Default Exports(One per module): This allows you to export only one module, which is the reason it showed you the error you have. This gives you the advantage of using a name of your choice in the file you import it from.
modules.js page
const module1=()=>console.log('module1');
export default module1
app.js
The page that is using the modules
import MyModule from './modules.js'
You can read more about it here
you can use named export or one as default and other as named export.
Define functions
function sum(a, b) {
return a + b
}
function sub(a, b) {
return a - b
}
function mul(a, b) {
return a * b
}
Define export
export { sum, sub, mul }
Import functions you need
import { sum, sub } from 'myfile'
or all the functions
import * as myfunctions from 'myfile'
and call as
sum(1+1) or myfunctions.sum(1+1)
src: https://flaviocopes.com/how-to-export-multiple-functions-javascript/
I am new to React or the coding background in general. And I am not sure what is the difference between the statements
import * as react from 'react'
and
import react from 'react'
Thanks in advance!
There are 3 types of most import commonly used imports.
Type 1
import * as A from 'abc';
This will import everything which is marked as export in abc. You can access them using below code.
A.Component
Type 2
import {A} from 'abc';
This will import A from abc, containing something like this:
export const A = () => {};
Type 3
import A from 'abc';
This will import the default export from abc as A. The export can look like this:
const B = () => {}; // The name "B" is not exported, only the value.
export default B; // at the end of component
Pattern import * as React from 'react is related to the use of type systems in React like Flow or Typescript. Using import React from 'react' has led to issues with importing types definitions. For now in Typescript you can use allowSyntheticDefaultImports flag, which resolves this issue and imports all types even if you use import React from 'react'.
In general, for ES2015 (ES6) modules
import * as name from 'module';
is a namepace import that indicates that all exported objects are to be placed in the name namespace. You can then do:
name.blabla1
name.blabla2
etc ...
The namespace is not callable. So you cannot do:
name();
While:
import name from 'module';
is a default import that is equivalent to:
import {default as name} from 'module';
You're importing only the default object from the module.
In the case of React, the confusion maybe/probably arises from the fact that React's default export is ... React (Babel adds the default export for interoperability reasons). Strictly speaking, the syntax to use is:
import * as React from 'react';
or
import {Whatever} from 'react';
The following work only because of the transformation by Babel (not 100% sure):
import React from 'react';
import React, { Whatever } from 'react';
For those using TypeScript, prior to version 2.7, the default was to treat:
import * as name from 'module';
as being equivalent to:
const name = require('module');
and:
import name from 'module';
as being equivalent to:
const name = require('module').default;
Since version 2.7, if your compiler settings specify "esModuleInterop" to true (which is recommended), then you can use the ES2015 syntax behavior.
I am receiving the following error when trying to run my React app:
./src/components/App/App.js
Attempted import error: 'combineReducers'
is not exported from '../../store/reducers/'.
Here's how I'm exporting combineReducers:
import { combineReducers } from 'redux';
import userReducers from './userReducers';
import articleReducers from './articleReducers';
export default combineReducers({
userReducers,
articleReducers
});
and here's how I'm importing it in App.js:
import { combineReducers } from '../../store/reducers';
What's incorrect in how I'm exporting combineReducers?
import { combineReducers } from '../../store/reducers';
should be
import combineReducers from '../../store/reducers';
since it's a default export, and not a named export.
There's a good breakdown of the differences between the two here.
i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.
import React, { Component } from "react";
export class Counter extends Component { // type this
export default Counter; // this is eliminated
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important.
if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me. 🙂
This is another option:
export default function Counter() {
}
Take into consideration that if you are using a named export you don't need curly brackets:
export const Component
->
import {ComponentName}
Only the default exported component be imported with curly brackets:
export default
->
import ComponentName
Maybe i'm late too but i had a similar problem with folders inside of component folder. i changed the folder's name with Capital letter. it worked for me.
If changing the import doesn't help maybe you just need to run yarn install or npm install (or whatever you're using) and restart your server. Worked for me.
Be sure to Capitalize the name of the constant variable you're exporting inside the component. When you Import the component elsewhere you should also check that its first letter is capitalized since this is one of the ways React uses to identify its components.
inside component:
import React from 'react';
export const Component = (props) => (...)
And then, when importing:
import {Component} from '../location/file'
Consider checking for any file renamings that git hasn't been instructed to track with git mv
I thought the line:
import { FETCH_WEATHER } from "../actions/index";
means: we don't import the whole object, but import the obj.FETCH_WEATHER from the file ../actions/index.js
One example is, we use
import React, { Component } from "react";
And it is like, we import from "react", let's call it here as obj, and name it React in our own file, and obj.Component, we name it as Component in our own file.
(1) is that true?
(2) in the file ../actions/index.js, the content is actually:
export const FETCH_WEATHER = "FETCH_WEATHER";
so there is no object, and no key / value pair to speak of. So what does import { FETCH_WEATHER } mean?
Mozilla Developer Network has a really good documentation on imports in ES6:
import – JavaScript | MDN
Basically the imports within the curly brackets are named imports, and must match a named export from the library you're importing from. That can be any object / function / constant that is exported.
Using import without curly brackets imports the default variable / object / function from the library. The default export has default keyword as part of the export statement: export default someVariable
The module may export one default object and many named items.
It is default module export:
const MyClass = (props) => (
<div/>
)
export default MyClass
We can import it like this:
import MyClass from "../actions"
The curly braces allows to export named items, so if we have such exports:
const myConst = "The Text"
const myHelper = (num) => 2*num
export default MyClass
export {myHelper, myConst}
We can import its like this:
import MyClass, {myHelper, myConst} from "../actions"
There is not need to add index at path - it is add by default. So write "../actions" enough instead of "../actions/index"
In React, Curly Braces are used to import single(specific) property, whereas
the word without braces is import entire object form that file.
Eg.,
import React, { Component } from 'react';
Here the word React represents to import entire object from the file 'react'
{Component} means we specify to import the particular property from the file.