What is the use of Curly Braces in an ES6 import statement

I see that there are two different ways to import

import React from 'react' import { render } from 'react-dom' 

the second has brackets. So what is the difference between the two? and when should i add brackets? thanks

+19
reactjs redux
source share
4 answers

The difference between whether components should be imported in brackets or without them is how they are export .

There are two types of export

  1. Default Export
  2. Named Export

A component can have one default export and zero or more named exports

If the component is the default export, you need to import it without parentheses. for example

 export default App; 

Import it's like

 import App from './path/to/App'; 

Named exports can be either

 export const A = 25; 

or

 export {MyComponent}; 

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 multiple named exports, you can even mix them during import

 import App, {A as SomeName} from './path/to/file'; 

Similarly, in the case of react and react-dom , React and ReactDOM is default exports by Component named export react render react-dom default exports , respectively, while, for example, Component is named export in react and render is named export in react-dom . That is why you can do

 import ReactDOM from 'react-dom'; 

and then use

 ReactDOM.render() 

or use as indicated in your question.

+31
source share

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 as follows:

 import sum, { sub, sqr } from './primitives'; 

In this case, sum is called "Export by default", and the module can contain only one "Export by default".

sub and sqr are called "Named Export", and a module can contain several named export data.

+2
source share

No need to add parentheses if you export by default. you can only have a default module.

case1:

default function export (num1, num2) {return num1 + num2; }

Case 2:

sum of function (num1, num2) {return num1 + num2; }

export {sum as default};

case3:

sum of function (num1, num2) {return num1 + num2; }

export default amount;

you can import by default

import the amount from "./test.js";

console.log (sum (1, 2));

0
source share

Curly braces are used to import a single(specific) property , while a word without braces is an import entire object from this file.

For example.,

 import React, { Component } from 'react'; 

Here the word React represents to import the entire object from the file 'react'

{Component} means that we specify to import a particular property from the file.

0
source share

All Articles