0

Can someone explain the differences between export default Example; , export { default } Example;, and export default class Example extends Component {};

I've seen all 3 used in examples online. I've run into issues using export default class Example extends Component {} where react says that I can only have 1 default export in a module.

Which one(s) do I avoid, are there advantages to using one over the other?

Brian Patrick
  • 333
  • 5
  • 18

1 Answers1

2

Let's look at an example class

export default class MyComponent extends React.Component {
 ...
}

Another example of the same component could be written as follows

export class MyComponent extends React.Component {
 ...
}
export default MyComponent

Finally, you could have more than one class available in a component file.

export MyComponent extends React.Component {
 ...
}
export MyComponent2 extends React.Component {
 ...
}

Now, when I import MyComponent using

import MyComponent from "../components/MyComponent"

The default class will be exported.

Now, if I want to export specific components from a file that has components combined. I can do the following:

import { MyComponent2 } from "../components/MyComponent"

The brackets allow you to import a single feature of the class/object/file that you are importing. Syntax aside momentarily, this is the behavior that the default keyword creates. This allows you to import only specific functionality from libraries and frameworks instead of having to import everything, which is what "default" usually implies.

This was already answered here: Javascript (ES6), export const vs export default

Aaron Franco
  • 1,560
  • 1
  • 14
  • 19