Why sometimes import has {} and sometimes doesn't?

Question

Why sometimes import has {} and sometimes doesn’t?

Answer

The way on how we import the content from another file will always depend on how it is being exported, for example when we see:

import ComponentName from './ComponentName';

it means that whatever ComponentName is, it is a default export, which means that it is the only export of it’s kind, this approach is mainly implemented with objects, or some classes like in the case of components:

class ComponentName extend React.Component {
...
}

export default ComponentName;

Then when we see:

Import { ComponentName } from './ComponentName';

It just means that it is a named export by having the export keyword assigned to it which makes it like a property of an exported object:

export class ComponentName extends React.Component {
  ...
}

As a bonus, we can also import from named exports using aliases:

import * as allComponentMethods from './ComponentName';
/* which reads: import all under the name allComponentMethods*/

import { ComponentName as NamedExported } from './ComponentName';
/*here we change the name on the name export*/
17 Likes

Very helpful, thank you.

Can you please elaborate on this? I’m still new to React, and the way I interpret this that we use import componentName without brackets when we are using export default on the component.

In other words export default is for when we are importing in more than one place, and we use the brackets for a single import? Is that correct?

Edit: I think I understand now. The brackets are for when we only want to export certain things from another component and not necessarily the whole thing?

5 Likes

here, the extend should be corrected to extends

@jbendz
first of all let’s talk about when to use curly braces:
When you export with export default you can import ** without curly braces**.
When you export with named export ** you import ** with curly braces.

Secondly, when do we use export default or named export?
export default is best used when we want to export a whole class or object in a file.
named export is best used when we want to export some variables(could be a class, function or any valid JS) which could be all or just some of the variables in a file. This allows us to export only the the variables we need.

17 Likes