Writing a short blog post about named vs. default exports in React will serve as somewhat of a sanity check for myself.
(Scroll down for the tl;dr version!)
ES6 provides the ability to import and export modules, and more specifically, within React this means that you can easily create a stateless component and then later import it elsewhere and use its functionality there. Let’s get right to it…
Named exports
You can have multiple named exports from within a file. The only 2 catches with named exports are that when it comes time to import them, you have to use curly braces as well as use the same name when importing them. Here’s an example:
export const function namedExport() {
console.log("This is a named export!")
}
export const function yetAnotherNamedExport() {
console.log("This is a named export!")
}
And now when it comes time to import the above named functions, it would look like the following (Note the usage of the same name, as well as curly braces):
import { namedExport } from './namedExports'
import { yetAnotherNamedExport } from './namedExports'
Default exports
One of the main differences between named vs. default exports is that you can only have ONE default export per file whereas we saw with named exports you can have virtually as many as you’d like. Another difference is that when it’s time to import a default export, you can rename it… and you don’t have to use curly braces:
const function defaultExport() {
console.log("This is a default export!")
}
export default defaultExport
And now when it’s time to import the above default export:
import defaultExport from './defaultExports'
OR you can do this:
import literallyAnyNameYouWant from './defaultExports'
And when thinking about the logic behind this, the above example starts to make sense: When you have a default export, there can literally only be ONE export, so when it comes time to import it, it doesn’t matter what name you import it as because no matter what, it can only be ONE object that was exported to then import.
tl;dr version – you can have multiple named exports from a file but when it comes time to import them their name matters, as well as curly braces. When talking about default exports, there can only be one default export per file, and their name isn’t important when importing them, nor do you have to use curly braces.