Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between import React and import { Component } syntax [duplicate]

Say, we are using React with ES6. We import React and Component as

import React from 'react' import { Component } from 'react' 

Why the syntax difference? Can't we use as specified below?

import Component from 'react' 
like image 307
prasad.surase Avatar asked Jan 20 '17 16:01

prasad.surase


People also ask

What is the difference between import and import?

In simple terms, imports mean movement of goods from a foreign country to the domestic country. Re-imports means import of domestic goods which already exported from the domestic country to a foreign country.

What is import * In React?

Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.

Which syntax is used to import just the component from the React library?

Importing Components from React Bootstrap It is the basic syntax that's used to import the specific components from the library, but you can still import it using other ways that you will learn in the next section of this guide.


2 Answers

Here are the docs for import.

import React from 'react' 

The above is a default import. Default imports are exported with export default .... There can be only a single default export.

import { Component } from 'react' 

But this is a member import (named import). Member imports are exported with export .... There can be many member exports.

You can import both by using this syntax:

import React, { Component } from 'react'; 

In JavaScript the default and named imports are split, so you can't import a named import like it was the default. The following, sets the name Component to the default export of the 'react' package (which is not going to be the same as React.Component:

import Component from 'react'; 
like image 181
Davin Tryon Avatar answered Nov 16 '22 00:11

Davin Tryon


Component is a named export. e.g. Therefore, it must be destructured with {}.

React is a default export for React from 'react' is correct. e.g. export default React

like image 32
D. Walsh Avatar answered Nov 16 '22 02:11

D. Walsh