Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/41337709/what-is-use-of-curly-braces-in-an-es6-import-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
375 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

  1. Default Export
  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...