Solve - Only one default export allowed per module in React

avatar

Borislav Hadzhiev

Thu Mar 03 20222 min read

Solve - Only one default export allowed per module in React #

The error "Only one default export allowed per module" occurs when we have more than 1 default export in a file. To solve the error, replace the second default export with a named export or move the value to another file to be able to use another default export.

Here is an example of how the error occurs.

App.js
export default function App() { // 👈️ default export return <div>hello</div>; } // ⛔️ Error: Parsing error: Only one // default export allowed per module. export default function Button() { // 👈️ default export return <button>Submit</button> }

We can only have a single default export per file, so we have to move the second default export to another file or convert it to a named export.

Here is how you would convert the second export to a named export.

App.js
export default function App() { // 👈️ default export return <div>hello</div>; } export function Button() { // 👈️ named export return <button>Submit</button>; }

And here is how you would import the variables into another file.

index.js
// 👇️ default and named import import App, {Button} from './App'; console.log(App); console.log(Button);

We had to wrap the named import in curly braces. You can have only one default export per file, but you can have as many named exports as necessary.

If you don't want to use a named export, move the second component to a separate file and make sure to stick to a maximum of 1 default export per file.

In my experience, most real world codebases exclusively use named exports and imports because they make it easier to leverage your IDE for autocompletion and auto-imports.
You also don't have to think about which members are exported with a default or named export.

Here is how you would convert the example above to use only named exports and imports.

App.js
export function App() { // 👈️ named export return <div>hello</div>; } export function Button() { // 👈️ named export return <button>Submit</button>; }

And here is how you would import the named exports.

index.js
// 👇️ named imports import {App, Button} from './App'; console.log(App); console.log(Button);

This is much better than having to remember which values you exported as default, and which as named.

The less you have to think about implementation details, the more you can focus on domain-specific logic in your application.

Use the search field on my Home Page to filter through my more than 1,000 articles.