"does not contain a default export" - Let's understand what went wrong.

Named Export vs Default Export

"does not contain a default export" - Let's understand what went wrong.

Okay, so you are finally working on a react project for your portfolio or building a side project and you come across this error "componentName.js does not contain a default export", if you don't know what this error means or what "default export" means then, let's try to understand it and see how we can solve this error.

Types of exports

There are 2 types of export statements.

export function MyComponent() {}
vs
export default MyComponent

Exports without a default tag are Named exports.

  • Named exports use the name of the function or class as their identifier.

Exports with the default tag are Default exports.

  • Default exports are created by including a default tag in the export.

The difference

The main difference between these exports comes when importing these exported functions/classes.

Named exports

  • Named exports are imported using the same name of the component as it was exported with, inside curly brackets.

  • We can have multiple exports in a single file.

  • We can assign a new name to the exported function using "as" keyword.

//my-functions.js
export const MyFunction1 = () => {};

export const MyFunction2 = () => {};

export const MyFunction3 = () => {};

//App.js
import {MyFunction1, MyFunction2 as SecondFunction, MyFunction3} from "./my-functions.js"

Default exports

  • Default exports can be imported using the same name of the component or whatever name you want. The name is imported without curly brackets.

  • We can have only one export in a single file.

  • We can just use another name for the function.

//my-functions.js
export default MyFunction1 = () => {};

//App.js
import MyFunction1 from "./my-functions.js"
or
import WhateverName from "./my-functions.js"

You can combine default and named exports in a single file, however importing remains the same, named exports are in curly brackets, default is plaintext.

//my-functions.js
export const MyFunction1 = () => {};

export default MyFunction2 = () => {};

//App.js
import MyFunction2, { MyFunction1 } from "./my-functions.js"

Named and Default exports are es6 features and are not specific to react ecosystem.

The Solution

As you might have guessed already, the solution to our error is:

  • To add curly brackets to the component name in the import statement.
  • or, add default tag to the export statement of that component.

Conclusion

While you can use any of the 2 ways to export your components, its good to know the difference because it deepens your understanding and helps enable better file structure and code readability.

Cover Photo by Nubelson Fernandes on Unsplash

Did you find this article valuable?

Support Syed Muzzammil Hassan Abedi by becoming a sponsor. Any amount is appreciated!