Difference between import React and import { Component } syntax
ReactjsEcmascript 6Reactjs Problem Overview
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'
Reactjs Solutions
Solution 1 - Reactjs
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';
Solution 2 - Reactjs
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
Solution 3 - Reactjs
If in any file you are exporting something by default with statement like export default React
, then that can be imported like import React
.
For other exports which are not default, we need to specify what we actually want to import by closing that in parentheses like import { Components}
.