DEV Community

Ajay Baraiya
Ajay Baraiya

Posted on

React Default Export Vs Named Export? #Beginners

We have our component file.
When we export it like below.

//MyFunc.js file 
const MyFunc = () => <h1>Default Export<h1/>
export default MyFunc;
Enter fullscreen mode Exit fullscreen mode

Than we can import that component with different name like belwo.

import MyChoiceOfName from "./MyFunc"
//so we can use 
<MyChoiceOfName /> //here.
Enter fullscreen mode Exit fullscreen mode

But when we don't use export default and directly export our component as below.

//NameExpo.js file 
export const NameExpo = () => <h1>Named Export<h1/>
//As we did not specify name here and so it has to take some name to export, so it will take componenet name.
Enter fullscreen mode Exit fullscreen mode

And while importing it we must need to import using it's name.\

import NameExpo from "./NameExpo" //Notice here we have both file and delcared name same i.e. NameExpo
//so we can use 
<NameExpo /> //here.
Enter fullscreen mode Exit fullscreen mode

What if you want to export multiple components from one single .js file?

It is possible using Named export.

//NameExpo.js file 
export const MyNameExpo1 = () => <h1>Named Export 1<h1/>
export const MyNameExpo2 = () => <h1>Named Export 2<h1/>
export const MyNameExpo3 = () => <h1>Named Export 3<h1/>
Enter fullscreen mode Exit fullscreen mode

And in importing

import MyNameExpo1 from "./NameExpo" 
import MyNameExpo2 from "./NameExpo" 
import MyNameExpo3 from "./NameExpo" 
//so we can use 
<MyNameExpo1 /> //here.
<MyNameExpo2 /> //here.
<MyNameExpo3 /> //here.
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)