Default exports & Name exports
Moazam Ali
Posted on February 11, 2023
The export
declaration lets you to export a specific part from JavaScript files which can be imported into other files using import
declaration for reusing. The default
prefix marks that function/class as an entry point (main function) in a file.
The export default
prefix is a standard JavaScript Syntax(not specific to react). It lets you mark the main function in a file so that you can later import it from other files.
For example:
Exporting a Button component by Default export
export default Button
Exporting a Button component by Name export
export Button
- You can use both(default & name) of them in the same file.
- A file cannot have more than one default export but it can have as many named exports.
- How you export your component tells you how to import it because if you try to import a default export the same way you do a named export, it will log an error.
Default export
Export syntax:
export default function Button() {...}
Import syntax:
import Button from ‘./button.js’
Name export
Export syntax:
export function Button() {...}
Import syntax:
import { Button } from ‘./button.js’
- When you are importing a component with
export default
, you can put any name you want afterimport
. For example,import Hello from ‘./button.js’
instead ofimport Button from ‘./button.js’
. While in named imports, the name has to match on both sides.
Summary
- Use default exports when you have one component in the file and use name exports when your file exports multiple components.
- Also, components without names like
export default () => {...}
are discouraged because they make debugging harder. - To reduce the potential confusion between default and name exports, you can stick to only one style (default or named). For default export, each file will need to export only one component. While for name export, each file can export multiple components.
Wrapping up!
That's all for this article, hope you learned something. Thanks for reading, catch you later.
Let’s connect on LinkedIn.
You can also buy me a coffee that would help me grow as a frontend developer :)
Posted on February 11, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 16, 2024